Javascript 处理响应 - SyntaxError:使用模式时意外结束输入:'no-cors'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43317967/
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
Handle response - SyntaxError: Unexpected end of input when using mode: 'no-cors'
提问by Chilliggo
I tried a ReactJS fetch call to a REST-API and want to handle the response. The call works, i get a response, which i can see in Chrome Dev Tools:
我尝试了对 REST-API 的 ReactJS fetch 调用并想要处理响应。通话有效,我得到了回应,我可以在 Chrome 开发工具中看到:
function getAllCourses() {
fetch('http://localhost:8080/course', {
method: 'POST',
mode: 'no-cors',
credentials: 'same-origin',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
objectClass: 'course',
crud: '2'
})
}).then(function (response) {
console.log(response);
return response.json();
}).catch(function (err) {
console.log(err)
});
}
When i try to handle the response, i got a "SyntaxError: Unexpected end of input" at
当我尝试处理响应时,我在
return response.json();
The console.log looks like this:
console.log 看起来像这样:
My Response JSON looks like this, it is valid, i checked it with jsonlint:
我的响应 JSON 看起来像这样,它是有效的,我用 jsonlint 检查了它:
[
{
"0x1": {
"users": [],
"lectures": [],
"owner": "0x2",
"title": "WWI 14 SEA",
"description": null,
"objectClass": "course",
"id": "course_00001"
},
"0x2": {
"username": "system",
"lectures": [],
"course": null,
"solutions": [],
"exercises": [],
"roles": [
"0x3",
"0x4",
"0x5"
],
"objectClass": "user",
"id": "user_00001"
},
"0x3": {
"roleName": "ROLE_ADMIN",
"objectClass": "role",
"id": "role_00001"
},
"0x4": {
"roleName": "ROLE_STUDENT",
"objectClass": "role",
"id": "role_00002"
},
"0x5": {
"roleName": "ROLE_DOCENT",
"objectClass": "role",
"id": "role_00003"
}
}
]
回答by sideshowbarker
You need to remove the mode: 'no-cors'setting from your request. That mode: 'no-cors'is exactly the cause of the problem you're having.
您需要mode: 'no-cors'从请求中删除该设置。这mode: 'no-cors'正是您遇到问题的原因。
A mode: 'no-cors'request makes the response type opaque. The console-log snippet in the question clearly shows that. And opaquemeans your frontend JavaScript code can't see the response body or headers.
甲mode: 'no-cors'请求做出反应类型opaque。问题中的控制台日志片段清楚地表明了这一点。并且opaque意味着您的前端 JavaScript 代码无法看到响应正文或标头。
https://developer.mozilla.org/en-US/docs/Web/API/Request/modeexplains:
https://developer.mozilla.org/en-US/docs/Web/API/Request/mode解释:
no-cors— JavaScript may not access any properties of the resultingResponse
no-cors— JavaScript 可能无法访问结果的任何属性Response
So the effect of setting mode: 'no-cors'is essentially to tell browsers, “Don't let frontend JavaScript code access the response body or headers under any circumstances.”
所以设置的效果mode: 'no-cors'本质上是告诉浏览器,“在任何情况下都不要让前端 JavaScript 代码访问响应正文或标题。”
I imagine you're setting mode: 'no-cors'for the request because the response from http://localhost:8080/coursedoesn't include the Access-Control-Allow-Originresponse header or because your browser's making an OPTIONSrequest to http://localhost:8080because your request is one that triggers a CORS preflight.
我想您正在设置mode: 'no-cors'请求,因为来自的响应http://localhost:8080/course不包含Access-Control-Allow-Origin响应标头,或者因为您的浏览器正在向 发出OPTIONS请求,http://localhost:8080因为您的请求是触发CORS 预检的请求。
But setting mode: 'no-cors'is not the solution to those problems. The solution is either to:
但是设置mode: 'no-cors'并不是解决这些问题的方法。解决方法是:
configure the
http://localhost:8080server to send theAccess-Control-Allow-Originresponse header and to handle theOPTIONSrequestor set up a CORS proxy using code from https://github.com/Rob--W/cors-anywhere/or such (see the How to use a CORS proxy to get around “No Access-Control-Allow-Origin header” problemssection of the answer at No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API)
配置
http://localhost:8080服务器以发送Access-Control-Allow-Origin响应头并处理OPTIONS请求或使用https://github.com/Rob--W/cors-anywhere/等代码设置 CORS 代理(请参阅如何使用 CORS 代理绕过“No Access-Control-Allow-Origin 标头” ”问题部分在No 'Access-Control-Allow-Origin' 标头中的答案存在于请求的资源上——当尝试从 REST API 获取数据时)
回答by Kmaschta
In your thenyou should check if the response is OK before returning response.json:
在您的then返回之前,您应该检查响应是否正常response.json:
.then(function (response) {
if (!response.ok) {
return Promise.reject('some reason');
}
return response.json();
})
If you want to have the error message in your rejected promise, you can do something like:
如果您想在被拒绝的承诺中包含错误消息,您可以执行以下操作:
.then(function (response) {
if (!response.ok) {
return response.text().then(result => Promise.reject(new Error(result)));
}
return response.json();
})
回答by Temitope Ruth Elodimuor
I know this answer might be super late and might have been resolved but i just had the same issue today and I just needed to add a ',' at the end of the headers hash and i stopped getting the error
我知道这个答案可能太晚了,可能已经解决了,但我今天遇到了同样的问题,我只需要在标题散列的末尾添加一个“,”,我就不再收到错误了
export function addContacts(formData) {
return(dispatch) => {
dispatch({type: 'POSTING_CONTACTS'});
console.log(formData)
return fetch(uri, {
method: 'POST',
body: JSON.stringify({contact: {name: formData.name, phone_number: formData.phoneNumber}}),
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
})
.then(response => {
return response.json()
}).then(responseJSON => {
console.log(responseJSON)
return dispatch({type: 'ADD_CONTACT', payload: responseJSON});
})
}
}
回答by Juboraj Sarker
Simply copy the following code and paste it on your web.configfile under <system.webServer>tag.
只需复制以下代码并将其粘贴到标签下的web.config文件中即可<system.webServer>。
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
回答by Roman
You can avoid the problem with CORS policy by adding in the header of php or another server endpoint the row:
您可以通过在 php 或其他服务器端点的标题中添加行来避免 CORS 策略的问题:
<?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;
});


