从源“http://...”访问“...”处的 XMLHttpRequest 已被 CORS 策略阻止

问题描述 投票:0回答:2
所以我的问题是:

每当我尝试从我的网页(同一台机器,不同端口)向我的 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

javascript http xmlhttprequest
2个回答
1
投票
答案就在

这里

这是您浏览器的隐私问题,有两种方法可以解决它:

    允许浏览器上来自任何地方的请求
  1. 将控制器放入标头访问控制信息中。
完整答案在上面的链接中


0
投票
我遇到了这个问题:从源“React app URL”访问“Node.js 服务器 URL”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:无“访问控制-”请求的资源上存在“Allow-Origin”标头。

我通过在我的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(); });
    
© www.soinside.com 2019 - 2024. All rights reserved.