每当我尝试从我的网页(同一台机器,不同端口)向我的 HTTP 服务器发出 XMLHttpRequest 时,我就会被此错误阻止:
Access to XMLHttpRequest at 'localhost:8081' from origin 'http://localhost:8080' has been blocked by CORS policy:
Cross-origin requests are only supported for protocol schemes: HTTP, data, chrome, chrome-extension, brave, chrome-untrusted, HTTPS.
为什么会出现这种情况?示例客户端(浏览器):
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
// Use data...
};
xhttp.open("GET", "localhost:8081", true);
xhttp.send();
示例服务器(NodeJS、HTTP 库):
const server = http.createServer((req, res) => {
if(req.url != '/') return res.end('404');
res.writeHead(200, {
'Content-Type': 'text/html'
})
const json = {
// Data...
}
res.write(JSON.stringify(json))
res.end()
});
server.listen(8081)
解决了,感谢评论中的昆汀:D
我通过在我的index.js(主服务器文件)中添加以下代码行解决了这个问题:
app.use((req, res, next) => {
res.header(
"Access-Control-Allow-Origin",
"React app URL"
);
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
res.header("Access-Control-Allow-Headers", "Content-Type");
next();
});