Can't perform get request with axios and ReactJS
Solution 1
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
});
Solution 2
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
nix86
Updated on June 04, 2022Comments
-
nix86 almost 2 years
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?
-
RIYAJ KHAN about 6 yearsAt the backend what r u using?
-
-
nix86 about 6 yearsAnd also the server must be configured properly. In case you use JBoss here is a link showing how to do it: forum.camunda.org/t/enable-cors-on-wildfly/673/2