fetch() 输入意外结束
fetch() unexpected end of input
我正在使用 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))
不透明的回应
对 cross-origin 资源的 no-cors
请求的响应具有 response type of 'opaque'。如果您在尝试将其转换为 JSON 之前记录响应,您将看到一种“不透明”类型。
不透明类型是 listed as "severely restricted",如 whatwg.org 上的获取规范中所述。
An opaque filtered response is a filtered response whose type is "opaque", url list is the empty list, status is 0, status message is the empty byte sequence, header list is empty, body is null, and trailer is empty.
如 Google's docs on the opaque type 所述,当类型不透明时,当前无法读取它们。
An opaque response is for a request made for a resource on a different origin that doesn't return CORS headers. With an opaque response, we won't be able to read the data returned or view the status of the request, meaning we can't check if the request was successful or not. With the current fetch() implementation, it's not possible to make requests for resources of a different origin from the window global scope.
在您的服务器上启用 CORS 支持
这可以是 environment-dependent 或 language-dependent。例如,您可以通过更改服务器配置来更改 Nginx 环境中的 CORS 设置,或者您可以在应用程序代码中指定 headers,例如 PHP.
我强烈推荐阅读 Mozilla documentation on CORS requests and also Access-Control-Allow-Origin。
PHP中的示例:
<?php
header("Access-Control-Allow-Origin: *"); // "*" could also be a site such as http://www.example.com
您需要在 php 的 header 或其他服务器端点中包含以下行:
<?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;
});
您遇到了 CORS 源策略问题。要解决此问题,您需要有权访问服务器端 API。特别是,您需要在 php 或另一个服务器端点的 header 中添加一行:
<?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 中包含:
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;
});
我遇到了同样的问题。在我的例子中,它不是由 'opaque' 的响应类型引起的,正如解决方案所指出的那样。
此代码会导致空响应错误,因为 '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;
(对于后来来但正在处理这个问题“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)
});
}
输入意外结束
// .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 的回答中...
我不知道这是怎么发生的,但我只是通过改变解决了它
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) : {})
})
})
我正在使用 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))
不透明的回应
对 cross-origin 资源的 no-cors
请求的响应具有 response type of 'opaque'。如果您在尝试将其转换为 JSON 之前记录响应,您将看到一种“不透明”类型。
不透明类型是 listed as "severely restricted",如 whatwg.org 上的获取规范中所述。
An opaque filtered response is a filtered response whose type is "opaque", url list is the empty list, status is 0, status message is the empty byte sequence, header list is empty, body is null, and trailer is empty.
如 Google's docs on the opaque type 所述,当类型不透明时,当前无法读取它们。
An opaque response is for a request made for a resource on a different origin that doesn't return CORS headers. With an opaque response, we won't be able to read the data returned or view the status of the request, meaning we can't check if the request was successful or not. With the current fetch() implementation, it's not possible to make requests for resources of a different origin from the window global scope.
在您的服务器上启用 CORS 支持
这可以是 environment-dependent 或 language-dependent。例如,您可以通过更改服务器配置来更改 Nginx 环境中的 CORS 设置,或者您可以在应用程序代码中指定 headers,例如 PHP.
我强烈推荐阅读 Mozilla documentation on CORS requests and also Access-Control-Allow-Origin。
PHP中的示例:
<?php
header("Access-Control-Allow-Origin: *"); // "*" could also be a site such as http://www.example.com
您需要在 php 的 header 或其他服务器端点中包含以下行:
<?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;
});
您遇到了 CORS 源策略问题。要解决此问题,您需要有权访问服务器端 API。特别是,您需要在 php 或另一个服务器端点的 header 中添加一行:
<?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 中包含:
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;
});
我遇到了同样的问题。在我的例子中,它不是由 'opaque' 的响应类型引起的,正如解决方案所指出的那样。 此代码会导致空响应错误,因为 '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;
(对于后来来但正在处理这个问题“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)
});
}
输入意外结束
// .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 的回答中...
我不知道这是怎么发生的,但我只是通过改变解决了它
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) : {})
})
})