Reputation: 3
I'm working with my Raspberry Pi. I have my raspberry Pi, that on the IP: 192.168.X.X/file.json give me a webpage containing data in json. While trying to built a web page that requests in that page with the following code:
$.getJSON('http://192.168.X.x:8080/file.json', function(data) {
//code }
It returns the an error on the browser:
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.
Can you tell me how to fix it? And where to put the code to fix it?
Upvotes: 0
Views: 2513
Reputation: 2801
Your issue is related to Cross-Origin Resource Sharing (CORS)
: basically, you cannot access a domain via Ajax if it's not allowed on the server side. This is a "security" feature on most modern browsers. You won't encounter this problem using command line such as curl or chrome's Postman extension.
Make sure the domain requesting the data (localhost
) is allowed in the Access-Control-Allow-Origin
header, as well as the http verb (GET
, POST
, PUT
... or *
for every http methods).
Basically, it comes down to add the two following headers to the http://192.168.X.x/
server's response:
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: *
If you use node.js
with Express
, you can do the following :
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();
});
Upvotes: 1
Reputation: 198
You need to configure your web server to set the appropriate CORS response headers.
Upvotes: 0