Reputation: 3037
I am developing a web application with ReactJS and I want to perform a GET request with axios. First I tried with the following line:
axios.get("http://localhost:8080/MyWebApplication/MyServlet").then(data=>{
//Code
});
But I got the following error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/WebApplication1/NewServlet. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
Later I tried to add a header to solve the problem
axios.get("http://localhost:8080/WebApplication1/NewServlet", {headers:{'Access-Control-Allow-Origin': '*'}}).then(data=>{
//code
});
But the problem persisted. What is wrong?
Upvotes: 3
Views: 17649
Reputation: 1057
The default for crossDomain is as follows:
false for same-domain requests, true for crossDomain requests
If you are making a same domain json request, and your site may redirect the request to another domain to serve the response (via HTTP 3XX), then you should set the crossDomain property to true so the response can be read by your calling script.
This gives you the advantage of retrieving JSON when making same origin requests, and the functionality of JSONP when making cross-origin requests. If CORS is active on the domain you redirect to then you can set jsonp: false in the request options.
axios.get("http://localhost:8080/WebApplication1/NewServlet",{ crossDomain: true }).then(data=>{
//Logic of your code
});
Upvotes: 4
Reputation: 3215
Access-Control-Allow-Origin
is a response header, not a request header. Your server should respond with Access-Control-Allow-Origin
- this is how it tells browser that some cross-origin requests are ok and should be allowed.
Reference: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
Upvotes: 4