【问题标题】:Access to XMLHttpRequest at '...' from origin 'http://...' has been blocked by CORS policy从源“http://...”访问“...”处的 XMLHttpRequest 已被 CORS 策略阻止
【发布时间】: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


【解决方案1】:

答案是here

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

  1. 在您的浏览器上允许来自任何地方的请求
  2. 将控制器放在头部访问控制信息中。

完整的答案在上面的链接中

【讨论】:

    猜你喜欢
    • 2019-04-28
    • 2023-03-09
    • 2019-11-11
    • 2019-09-01
    • 2020-11-11
    • 2019-07-09
    • 2020-10-12
    • 2020-01-26
    • 2021-03-08
    相关资源
    最近更新 更多