尝试连接到 Raspberry 时,请求的资源上不存在 'Access-Control-Allow-Origin' header

No 'Access-Control-Allow-Origin' header is present on the requested resource when trying to connect to Raspberry

我正在使用我的 Raspberry Pi。 我有我的 raspberry Pi,在 IP 上:192.168.X.X/file.json 给我一个包含 json 中数据的网页。在尝试使用以下代码构建一个在该页面中请求的网页时:

$.getJSON('http://192.168.X.x:8080/file.json', function(data) {
    //code  }

它 returns 浏览器错误:

XMLHttpRequest cannot load http://192.168.X.X:8080/file.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

你能告诉我如何解决吗? 在哪里放置代码来修复它?

您需要配置您的网络服务器以设置适当的 CORS 响应headers。

您的问题与 Cross-Origin Resource Sharing (CORS) 有关:基本上,如果服务器端不允许,您将无法通过 Ajax 访问域。这是大多数现代浏览器的 "security" 功能。使用 curl 或 chrome 的 Postman 扩展等命令行不会遇到此问题。

确保在 Access-Control-Allow-Origin header 中允许请求数据的域 (localhost) 以及 http 动词 (GET, POSTPUT... 或 *(每个 http 方法))。

基本上,将以下两个 header 添加到 http://192.168.X.x/ 服务器的响应中:

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: *

如果您将 node.jsExpress 一起使用,您可以执行以下操作:

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  // or res.header("Access-Control-Allow-Origin", "localhost");
  res.header("Access-Control-Allow-Headers", "*");
  next();
});