我正在使用我的 Raspberry Pi。 我有我的树莓派,IP:192.168.X.X/file.json 给我一个包含 json 数据的网页。在尝试构建一个网页时,使用以下代码在该页面中请求:
$.getJSON('http://192.168.X.x:8080/file.json', function(data) {
//code }
它在浏览器上返回错误:
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.
你能告诉我如何解决这个问题吗? 以及在哪里放置代码来修复它?
请您参考如下方法:
您的问题与Cross-Origin Resource Sharing (CORS)
相关:基本上,如果服务器端不允许,则无法通过 Ajax 访问域。这是大多数现代浏览器上的“安全”功能。使用命令行(例如curl 或chrome 的Postman 扩展)不会遇到此问题。
确保请求数据的域 (localhost
) 在 Access-Control-Allow-Origin
header 中以及 http 谓词 ( GET
、POST
、PUT
...或 *
对于每个 http 方法)。
基本上,归根结底是将以下两个 header 添加到 http://192.168.X.x/
服务器的响应中:
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: *
如果您将 node.js
与 Express
结合使用,您可以执行以下操作:
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();
});