fetch(url,{
method:'post',
mode:"cors", //允許跨域 no-cors不允許跨域
// credentials:"include", //跨域請求時是不帶cookie的,添加該屬性表示強制加入憑據頭,請求時就會攜帶cookie。但是如果加上這個屬性,那么服務器的Access-Control-Allow-Origin 就不能是‘*’,否則會報下面的錯誤。
headers:new Headers({
'Content-Type': 'application/x-www-form-urlencoded', // 指定提交方式為表單提交
}),
body:formdate
}) .then(function(response) {
return response.json();
}).then(function(json) {
console.log('parsed json', json);
}).catch(function(ex) {
console.log('parsing failed', ex);
})
跨域設置credentials:"include"時,如果服務器端設置Access-Control-Allow-Origin 為‘*’會報如下錯誤。可以去掉該請求頭的設置,只添加mode:'cors'屬性。
The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:8080' is therefore not allowed access.