fetch() 예기치 않은 입력 끝
fetch()를 사용하여 API 서버에서 데이터를 가져옵니다.오류는 다음과 같습니다.
Uncaught (in promise) SyntaxError: Unexpected end of input at
fetch.then.blob.
제가 뭘 잘못하고 있는지 말씀해 주시겠어요?
const weatherAPi ='https://www.metaweather.com/api/location/523920';
fetch(weatherAPi, {
mode: 'no-cors'
}).then(blob => blob.json())
.then(data => console.log(data))
불투명한 응답
에 대한 응답no-cors상호 참조 리소스에 대한 요청의 응답 유형은 'syslog'입니다.응답을 JSON으로 전환하기 전에 로그를 기록하면 "opaque" 유형이 표시됩니다.
불투명 유형은 whatwg.org의 가져오기 사양에 설명된 대로 "제한됨"으로 나열됩니다.
불투명 필터링 응답은 필터링된 응답으로, 유형은 "opaque", URL 목록은 빈 목록, 상태는 0, 상태 메시지는 빈 바이트 시퀀스, 헤더 목록은 비어 있음, 본문은 늘 및 트레일러는 비어 있습니다.
현재 불투명한 글자에 대한 Google 문서에서 설명한 바와 같이 불투명한 글자는 읽을 수 없습니다.
불투명 응답은 CORS 헤더를 반환하지 않는 다른 원본의 리소스에 대한 요청에 대한 응답입니다.응답이 불투명하면 반환된 데이터를 읽거나 요청 상태를 볼 수 없습니다. 즉, 요청 성공 여부를 확인할 수 없습니다.현재의 fetch() 실장에서는 윈도 글로벌스코프와는 다른 소스 요청을 할 수 없습니다.
서버에서 CORS 지원 활성화
환경에 따라 다르거나 언어에 따라 다를 수 있습니다.예를 들어 서버 구성을 변경하여 Nginx 환경 내에서 CORS 설정을 변경하거나 PHP와 같은 애플리케이션 코드 내에서 헤더를 지정할 수 있습니다.
CORS 요청 및 Access-Control-Allow-Origin에 대한 Mozilla 문서를 읽을 것을 강력히 권장합니다.
PHP의 예:
<?php
header("Access-Control-Allow-Origin: *"); // "*" could also be a site such as http://www.example.com
저도 같은 문제가 있었어요.내 경우, 해결 방법처럼 '오류'의 반응 유형에 의한 것이 아니었다.'fetch'는 본문이 비어 있는 응답을 받아들이지 않기 때문에 이 코드는 응답이 비어 있는 오류를 일으킵니다.
return fetch(urlToUser, parameters)
.then(response => {
return response.json()
})
.then((data) => {
resolve(data)
})
.catch((error) => {
reject(error)
})
대신, 내 경우에는 이것이 더 잘 작동합니다.
return fetch(urlToUser, parameters)
.then(response => {
return response.text()
})
.then((data) => {
resolve(data ? JSON.parse(data) : {})
})
.catch((error) => {
reject(error)
})
본문이 비어있어도 텍스트를 읽어도 오류가 나지 않습니다.그런 다음 데이터가 있는지 확인하고 해결합니다.도움이 되었으면 합니다:-)
반응이 좋았는데 저는 이걸 골랐어요.
const response = await fetch(url, {
method: 'GET',
headers: {
Authorization: 'Bearer ' + accessToken
}
});
const string = await response.text();
const json = string === "" ? {} : JSON.parse(string);
return json;
php 또는 다른 서버 끝점의 헤더에 다음 행이 있어야 합니다.
<?php
header('Access-Control-Allow-Origin: *');
//or
header('Access-Control-Allow-Origin: http://example.com');
// Reading JSON POST using PHP
$json = file_get_contents('php://input');
$jsonObj = json_decode($json);
// Use $jsonObj
print_r($jsonObj->message);
...
// End php
?>
POST 요청을 사용한 페치 코드 작동 모델은 다음과 같습니다.
const data = {
optPost: 'myAPI',
message: 'We make a research of fetch'
};
const endpoint = 'http://example.com/php/phpGetPost.php';
fetch(endpoint, {
method: 'POST',
body: JSON.stringify(data)
})
.then((resp) => resp.json())
.then(function(response) {
console.info('fetch()', response);
return response;
});
(나중에 오지만, 이 문제에 대처하고 있는 유저의 경우, 「예상치 않은 JSON 입력의 종료」)
URL이지만 을 알 수 없기 에 볼 수 .fetch에는 서버 또는 네트워크 장애라는 중요한 부분이 누락되어 있습니다.
fetch는, 되어 있는 , 에러를 「에러」를 「에러」로 합니다.json.
첫 번째 부터 확인해보겠습니다.then, 「 」의 경우입니다.resp.ok다음 중 하나:
async function fetchData() {
return await fetch('https://your-server.com/some-NOt-existing-url/')
.then(resp => {
if (!resp.ok) {
throw `Server error: [${resp.status}] [${resp.statusText}] [${resp.url}]`;
}
return resp.json();
})
.then(receivedJson => {
// your code with json here...
})
.catch(err => {
console.debug("Error in fetch", err);
setErrors(err)
});
}
피보의 대답에 덧붙여...
어떻게 이런 일이 일어났는지 모르겠지만, 그냥 바꿔서 해결했다.
return fetch(url, {
mode: "no-cors" // <----------------
})
.then((res)=>{
return res.text();
})
.then((data)=>{
console.log(data);
return new Promise((resolve, reject)=>{
resolve(data ? JSON.parse(data) : {})
})
})
로.
return fetch(url, {
mode: "cors" // <----------------
})
.then((res)=>{
return res.text();
})
.then((data)=>{
console.log(data);
return new Promise((resolve, reject)=>{
resolve(data ? JSON.parse(data) : {})
})
})
당신은 CORS 원산지 정책 문제를 만났다.이 문제를 해결하려면 서버 측 API에 액세스할 수 있는 권한이 필요합니다.특히 php 또는 다른 서버 엔드포인트 헤더에 행을 추가해야 합니다.
<?php
header('Access-Control-Allow-Origin: *');
//or
header('Access-Control-Allow-Origin: http://example.com');
// Reading JSON POST using PHP
$json = file_get_contents('php://input');
$jsonObj = json_decode($json);
// Use $jsonObj
print_r($jsonObj->message);
...
// End php
?>
또, 서버 엔드 포인트의 헤더에 없는 것을 확인해 주세요.
header("Access-Control-Allow-Credentials" : true);
POST 요청을 사용한 페치 코드 작동 모델은 다음과 같습니다.
const data = {
optPost: 'myAPI',
message: 'We make a research of fetch'
};
const endpoint = 'http://example.com/php/phpGetPost.php';
fetch(endpoint, {
method: 'POST',
body: JSON.stringify(data)
})
.then((resp) => resp.json())
.then(function(response) {
console.info('fetch()', response);
return response;
});
예기치 않은 입력 종료
// .then((response) => response.json()) . // commit out this part
https://github.com/github/fetch/issues/268
fetch(url, {
method: 'POST',
body: JSON.stringify(requestPayload),
headers: {
'Content-type': 'application/json; charset=UTF-8',
Authorization: 'Bearer ' + token,
},
})
// .then((response) => response.json()) . // commit out this part
.then((json) => {
console.log("response :- ", json);
getCheckedInTrailersList();
}).catch((error)=>{
console.log("Api call error ", error.message);
alert(error.message);
});
@Pibo 솔루션의 대안으로, 이 솔루션을 수정하는 대신fetch()클라이언트 측에서는 반환값의 무효를 체크하여 서버 측에서 수정할 수 있습니다.{} (오류)[](일본어판)
은 '보다 낫다'의 예시입니다.Node.js:
site.get("/api/get-industries", (req, res) => {
db.accountDB.getPresetData("Industries")
.then((result) => {
// If the result is null, return an empty array instead.
res.send(result ? result : []);
})
.catch((error) => {
res.status(500).send(error);
});
});
@KevBot은 나를 구한다.나는 우연히 그 문제를 만났다.요청 방식은 계속 작동하지만 갑자기 실패했습니다.이것은, 「no-cors」옵션을 fetch 메서드에 추가했기 때문입니다.여러 api를 요청합니다.어떤 이들은 그렇지 않은 선택지를 필요로 한다.그래서 코드를 다음과 같이 수정했습니다.
// determine whether add mode option to fetch method
const option =is_outer? {
mode: 'no-cors'
} : {};
ret = fetch(url, option).then(data => {
if (url.endsWith('txt')) {
return data.text()
} else {
const j = data.json();
...
언급URL : https://stackoverflow.com/questions/45696999/fetch-unexpected-end-of-input
'programing' 카테고리의 다른 글
| 리액트 테스트 라이브러리를 사용하여 장치 테스트에서 작동하도록 RizeObserver를 시뮬레이션하는 방법 (0) | 2023.04.02 |
|---|---|
| .htaccess & WordPress: RewriteRule에서 폴더 제외 (0) | 2023.04.02 |
| TypeScript - 각도:여러 줄의 문자열 (0) | 2023.04.02 |
| CSV/XLS를 JSON으로 변환하시겠습니까? (0) | 2023.04.02 |
| npm WARN referred tar@2.2.2: 이 버전의 tar는 더 이상 지원되지 않으며 보안 업데이트를 받지 않습니다.가능한 한 빨리 업그레이드해 주세요. (0) | 2023.04.02 |