后端Api位于端口5000上,前端客户端位于端口4000上。我已经实现了其他SO posts和MSDN的解决方案,但仍然出现错误。
已安装NPM软件包:
npm install --save cors
两台服务器的app.js文件的实现方式
: var cors = require('cors');
app.use(cors({
credentials: true,
}));
app.use((req, res, next) => {
res.append('Access-Control-Allow-Origin', ['*']);
res.append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.append('Access-Control-Allow-Headers', 'Content-Type, token, Content-Length, X-Requested-With, *');
next();
});
在客户端js中的实现:
var _HEADERS = new Headers({
"Content-Type": "application/json",
'Access-Control-Allow-Origin':"*",
"Access-Control-Allow-Credentials": true
});
let policy= {
mode: "cors",
cache: "no-cache",
headers: _HEADERS
};
return fetch(url, policy)
.then((resp) => {
console.log(resp);
// return resp.json();
})
.catch(function(e) {
console.log(e);
});
错误:
Access to fetch at 'http://localhost:5000/api/...}'
from origin 'http://localhost:4000' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested resource...