【发布时间】:2022-01-11 18:48:33
【问题描述】:
所以我的问题是:
每当我尝试从我的网页(同一台机器,不同端口)向我的 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)
已解决,感谢 cmets 中的 Quentin :D
【问题讨论】:
-
错字:您忘记了 URL 的
http://位。 -
当然,修复它会给你一个更常见的 CORS 错误,但无论如何你没有做任何事情来支持它。
-
与手头的问题无关,但
'Content-Type': 'text/html'和res.write(JSON.stringify(json))真的没有意义。 JSON 不是 HTML。 -
感谢您的帮助:D
标签: javascript http xmlhttprequest