Javascript fetch() 意外的输入结束
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45696999/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
fetch() unexpected end of input
提问by Matt
I am using fetch() to grab data from api server. My error looks like this:
我正在使用 fetch() 从 api 服务器获取数据。我的错误是这样的:
Uncaught (in promise) SyntaxError: Unexpected end of input at
fetch.then.blob.
Can you please tell me what am I doing wrong.
你能告诉我我做错了什么吗?
const weatherAPi ='https://www.metaweather.com/api/location/523920';
fetch(weatherAPi, {
mode: 'no-cors'
}).then(blob => blob.json())
.then(data => console.log(data))
回答by KevBot
A response for no-corsrequest to cross-origin resource has a response type of 'opaque'. If you log the response before trying to turn it to JSON, you will see a type of "opaque".
一种用于响应no-cors请求到跨源资源具有“不透明”的响应类型。如果您在尝试将其转换为 JSON 之前记录响应,您将看到一种“不透明”。
Opaque types are listed as "severely restricted".
不透明类型被列为“严格限制”。
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.
不透明过滤响应是类型为“不透明”的过滤响应,url列表为空列表,状态为0,状态消息为空字节序列,头部列表为空,正文为空,尾部为空。
They cannot currently be read when the type is opaque.
当类型不透明时,它们当前无法读取。
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 on a different origin from the window global scope.
不透明响应是针对不同来源的资源发出的请求,该请求不返回 CORS 标头。对于不透明的响应,我们将无法读取返回的数据或查看请求的状态,这意味着我们无法检查请求是否成功。使用当前的 fetch() 实现,不可能对来自 window 全局范围的不同来源的资源发出请求。
回答by Pibo
I had the same problem. in my case it wasn't caused by the response type of 'opaque' as the solution pointed. This code cause an error with empty response, because 'fetch' doesn't accept responses with empty body :
我有同样的问题。在我的情况下,它不是由解决方案指出的“不透明”的响应类型引起的。此代码导致响应为空的错误,因为 'fetch' 不接受具有空正文的响应:
return fetch(urlToUser, parameters)
.then(response => {
return response.json()
})
.then((data) => {
resolve(data)
})
.catch((error) => {
reject(error)
})
Instead, in my case this works better :
相反,在我的情况下,这效果更好:
return fetch(urlToUser, parameters)
.then(response => {
return response.text()
})
.then((data) => {
resolve(data ? JSON.parse(data) : {})
})
.catch((error) => {
reject(error)
})
Gettting the text doesn't give the error even with the empty body. Then check if data exists and resolve. I hope it helps :-)
即使正文为空,获取文本也不会出现错误。然后检查数据是否存在并解决。我希望它有帮助:-)
回答by Roman
You need to have in the header of php or another server endpoint the row:
您需要在 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
?>
Model of working fetch code with POST request is:
带有 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;
});
回答by ariel guzman
Lots of good responses but I chose this:
很多很好的回应,但我选择了这个:
const response = await fetch(url, {
method: 'GET',
headers: {
Authorization: 'Bearer ' + accessToken
}
});
const string = await response.text();
const json = string === "" ? {} : JSON.parse(string);
return json;
回答by Roman
You met with the CORS origin policy problem. To tackle this you need rights to access the server side API. In particular, you need to add a line in the header of php or another server endpoint:
您遇到了 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
?>
Also, make sure NOT to have in the header of your server endpoint:
另外,请确保不要在服务器端点的标头中包含:
header("Access-Control-Allow-Credentials" : true);
Model of working fetch code with POST request is:
带有 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;
});

