Axios ошибка cors

I'm making an API call using Axios in a React Web app. However, I'm getting this error in Chrome: XMLHttpRequest cannot load https://example.restdb.io/rest/mock-data. No 'Access-Control-Allow-Orig...

I’ll have a go at this complicated subject.

What is origin?

The origin itself is the name of a host (scheme, hostname, and port) i.g. https://www.google.com or could be a locally opened file file:// etc.. It is where something (i.g. a web page) originated from. When you open your web browser and go to https://www.google.com, the origin of the web page that is displayed to you is https://www.google.com. You can see this in Chrome Dev Tools under Security:

The same applies for if you open a local HTML file via your file explorer (which is not served via a server):

What has this got to do with CORS issues?

When you open your browser and go to https://website.example, that website will have the origin of https://website.example. This website will most likely only fetch images, icons, js files and do API calls towards https://website.example, basically it is calling the same server as it was served from. It is doing calls to the same origin.

If you open your web browser and open a local HTML file and in that HTML file there is JavaScript which wants to do a request to Google for example, you get the following error:

The same-origin policy tells the browser to block cross-origin requests. In this instance origin null is trying to do a request to https://www.google.com (a cross-origin request). The browser will not allow this because of the CORS Policy which is set and that policy is that cross-origin requests is not allowed.

Same applies for if my page was served from a server on localhost:

Localhost server example

If we host our own localhost API server running on localhost:3000 with the following code:

const express = require('express')
const app = express()

app.use(express.static('public'))

app.get('/hello', function (req, res) {
    // res.header("Access-Control-Allow-Origin", "*");
    res.send('Hello World');
})

app.listen(3000, () => {
    console.log('alive');
})

And open a HTML file (that does a request to the localhost:3000 server) directory from the file explorer the following error will happen:

Since the web page was not served from the localhost server on localhost:3000 and via the file explorer the origin is not the same as the server API origin, hence a cross-origin request is being attempted. The browser is stopping this attempt due to CORS Policy.

But if we uncomment the commented line:

const express = require('express')
const app = express()

app.use(express.static('public'))

app.get('/hello', function (req, res) {
    res.header("Access-Control-Allow-Origin", "*");
    res.send('Hello World');
})

app.listen(3000, () => {
    console.log('alive');
})

And now try again:

It works, because the server which sends the HTTP response included now a header stating that it is OK for cross-origin requests to happen to the server, this means the browser will let it happen, hence no error.

Just to be clear, CORS policies are security features of modern day browsers, to protect people from harmful and malicious code.

How to fix things (One of the following)

  • Serve the page from the same origin as where the requests you are making reside (same host).
  • Allow the server to receive cross-origin requests by explicitly stating it in the response headers.
  • If using a reverse proxy such as Nginx, configure Nginx to send response headers that allow CORS.
  • Don’t use a browser. Use cURL for example, it doesn’t care about CORS Policies like browsers do and will get you what you want.

Example flow

Following is taken from: Cross-Origin Resource Sharing (CORS)

Remember, the same-origin policy tells the browser to block
cross-origin requests. When you want to get a public resource from a
different origin, the resource-providing server needs to tell the
browser «This origin where the request is coming from can access my
resource». The browser remembers that and allows cross-origin resource
sharing.

  • Step 1: client (browser) request When the browser is making a cross-origin request, the browser adds an Origin header with the
    current origin (scheme, host, and port).

  • Step 2: server response On the server side, when a server sees this header, and wants to allow access, it needs to add an
    Access-Control-Allow-Origin header to the response specifying the
    requesting origin (or * to allow any origin.)

  • Step 3: browser receives response When the browser sees this response with an appropriate Access-Control-Allow-Origin header, the
    browser allows the response data to be shared with the client site.

More links

Here is another good answer, more detailed as to what is happening: https://stackoverflow.com/a/10636765/1137669

Hello, this is my request:

axios({ method: 'POST', url:${SERVER_ADDRESS}/api/v1/manager/restaurant/${restaurantName}/payment-methods, crossDomain: true, data: { payment_methods: checkedPayments }, }) .then(() => { dispatch(loadPayments(restaurantName)); }).catch((error) => { console.log(error); dispatch(paymentsError()); });

the server is laravel 5, it is responding with:

XMLHttpRequest cannot load http://localhost:8000/api/v1/manager/restaurant/accusamus/payment-methods. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

Server headers are set with CORS middleware like this:

    return $next($request)
        ->header("Access-Control-Expose-Headers", "Access-Control-*")
        ->header("Access-Control-Allow-Headers", "Access-Control-*, Origin, X-Requested-With, Content-Type, Accept")
        ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS, HEAD')
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Allow', 'GET, POST, PUT, DELETE, OPTIONS, HEAD');

Theese are the response headers, which I get when I use postman:

Access-Control-Allow-Headers →Access-Control-, Origin, X-Requested-With, Content-Type, Accept
Access-Control-Allow-Methods →GET, POST, PUT, DELETE, OPTIONS, HEAD
Access-Control-Allow-Origin →

Access-Control-Expose-Headers →Access-Control-*
Allow →GET, POST, PUT, DELETE, OPTIONS, HEAD
Cache-Control →no-cache
Connection →close
Content-Type →text/html; charset=UTF-8
Date →Sat, 03 Dec 2016 10:33:04 GMT
Host →localhost:8000
X-Powered-By →PHP/7.0.13
X-RateLimit-Limit →60
X-RateLimit-Remaining →59
phpdebugbar-id →0ff14bef1824f587d8f278c87ab52544

AXIOS sends preflight which is:

Request URL:http://localhost:8000/api/v1/manager/restaurant/accusamus/payment-methods
Request Method:OPTIONS
Status Code:200 OK
Remote Address:[::1]:8000
Response Headers
view source
Allow:GET,HEAD,POST
Cache-Control:no-cache
Connection:close
Content-Type:text/html; charset=UTF-8
Date:Sat, 03 Dec 2016 10:25:27 GMT
Host:localhost:8000
X-Powered-By:PHP/7.0.13

Request Headers
view source
Accept:/
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:localhost:8000
Origin:http://localhost:3000
Referer:http://localhost:3000/restaurant-profile/payment
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36

Am I doing something wrong? I can’t figure it how to do this. Witch Chrome plugin CORS everything works fine, but this is not the way.

Please help, help is really appreciated, spent hours with this.

I’m using axios to make a axios.get call in my redux action.js file.
In my component this action is performed on form submission.

I’m getting status 200 in my console but not getting any response back.
I’m getting the following error:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http:\\localhost:3000' is therefore not allowed access.

Has anybody came across such error too? Would you please share on how to resolve this.

Matthew Herbst's user avatar

asked Feb 2, 2016 at 21:28

user4076248's user avatar

3

The problem is not with axios. The issue is with the server. When you serve up data you must add the following headers, before sending it.

Access-Control-Allow-Origin
must be set to
*

Access-Control-Allow-Headers
must be set to
Origin, X-Requested-With, Content-Type, Accept

answered Jun 17, 2016 at 20:21

anthonynorton's user avatar

3

The first confusion I had tackling this problem was understanding what a preflight request means. So I will start from there.

Browsers send preflight requests whenever a request does not meet these criteria:

  1. HTTP methods matches one of (case-sensitive):
    • GET
    • POST
    • HEAD
  2. HTTP Headers matches (case-insensitive):
    • Accept
    • Accept Language
    • Content Language
    • Last-Event-ID
    • Content-Type, but only if the value is one of:
      • application/x-www-form-urlencoded
      • multipart/form-data
      • text/plain

Preflight requests are made with an OPTIONS method that includes three additional headers that your server may not be expecting if it is not configured for CORS. They are:

  • Access-Control-Allow-Headers
  • Access-Control-Allow-Origin
  • Access-Control-Allow-Methods

If the server isn’t configured for CORS, it simply responds with an empty header having HTTP status code 200. Once you have configured the server for CORS, you should include the headers listed above as headers supported by CORS.

That should clear the error and allow you communicate with the server.

Note: While your server can handle the custom header you created (in my case, Authorization for JWT authentication), it most likely won’t be configured for CORS request. If you have access to your server, simply find out how to configure CORS for that server.

For more information about CORS. See https://www.html5rocks.com/en/tutorials/cors/

answered Jan 12, 2017 at 6:38

erika_dike's user avatar

erika_dikeerika_dike

2514 silver badges7 bronze badges

0

Please try this.. it worked for my case { crossdomain: true }.

axios.get(`http://localhost:4000/api`,{ crossdomain: true }).then((result)=>{
        console.log("result",result.data.result.[0].name);
      }).catch((error)=>{
        console.log("Error hey",error);
      });

answered Apr 5, 2021 at 11:49

Pankaj Chauhan's user avatar

This worked for me:

axios.create({
    baseURL: "http://localhost:8088"
  }).get('/myapp/user/list')
    .then(function(response) {
      callback && callback(response);
      debugger;
    })

answered May 8, 2019 at 0:39

Roberto Rodriguez's user avatar

I’m using axios to make a axios.get call in my redux action.js file.
In my component this action is performed on form submission.

I’m getting status 200 in my console but not getting any response back.
I’m getting the following error:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http:\\localhost:3000' is therefore not allowed access.

Has anybody came across such error too? Would you please share on how to resolve this.

Matthew Herbst's user avatar

asked Feb 2, 2016 at 21:28

user4076248's user avatar

3

The problem is not with axios. The issue is with the server. When you serve up data you must add the following headers, before sending it.

Access-Control-Allow-Origin
must be set to
*

Access-Control-Allow-Headers
must be set to
Origin, X-Requested-With, Content-Type, Accept

answered Jun 17, 2016 at 20:21

anthonynorton's user avatar

3

The first confusion I had tackling this problem was understanding what a preflight request means. So I will start from there.

Browsers send preflight requests whenever a request does not meet these criteria:

  1. HTTP methods matches one of (case-sensitive):
    • GET
    • POST
    • HEAD
  2. HTTP Headers matches (case-insensitive):
    • Accept
    • Accept Language
    • Content Language
    • Last-Event-ID
    • Content-Type, but only if the value is one of:
      • application/x-www-form-urlencoded
      • multipart/form-data
      • text/plain

Preflight requests are made with an OPTIONS method that includes three additional headers that your server may not be expecting if it is not configured for CORS. They are:

  • Access-Control-Allow-Headers
  • Access-Control-Allow-Origin
  • Access-Control-Allow-Methods

If the server isn’t configured for CORS, it simply responds with an empty header having HTTP status code 200. Once you have configured the server for CORS, you should include the headers listed above as headers supported by CORS.

That should clear the error and allow you communicate with the server.

Note: While your server can handle the custom header you created (in my case, Authorization for JWT authentication), it most likely won’t be configured for CORS request. If you have access to your server, simply find out how to configure CORS for that server.

For more information about CORS. See https://www.html5rocks.com/en/tutorials/cors/

answered Jan 12, 2017 at 6:38

erika_dike's user avatar

erika_dikeerika_dike

2514 silver badges7 bronze badges

0

Please try this.. it worked for my case { crossdomain: true }.

axios.get(`http://localhost:4000/api`,{ crossdomain: true }).then((result)=>{
        console.log("result",result.data.result.[0].name);
      }).catch((error)=>{
        console.log("Error hey",error);
      });

answered Apr 5, 2021 at 11:49

Pankaj Chauhan's user avatar

This worked for me:

axios.create({
    baseURL: "http://localhost:8088"
  }).get('/myapp/user/list')
    .then(function(response) {
      callback && callback(response);
      debugger;
    })

answered May 8, 2019 at 0:39

Roberto Rodriguez's user avatar

Я пытаюсь оптравить post-запрос через axios на сервер вот таким путём:

axios
        .post('/authors', {...this.loginFields, ...this.registerFields})
        .then(response => {
	        if (response.data.result === 'success') {
            // success
          } else if (response.data.result === 'error') {
            // error
          }
        })
        .catch(error => console.error(error))

При этом я получаю следующую ошибку в консоли:
5f1acea867a61012174765.png

При вот таком запросе:
5f1ad078d7c63379855939.png

Однако, стоит поменять отправляемые данные на строку, и я не получаю эту ошибку. Т.е. этот код в порядке:

axios
        .post('/authors', JSON.stringify({...this.loginFields, ...this.registerFields}))
        .then(response => {
	        if (response.data.result === 'success') {
            // success
          } else if (response.data.result === 'error') {
            // error
          }
        })
        .catch(error => console.error(error))

При вот таком запросе:
5f1ad09202f8b759020957.png

При этом nginx настроен на отправку cors-заголовка вот так:

location / {
	add_header Access-Control-Allow-Origin *;
	try_files $uri $uri/ /index.php?$args;
}

В чём тут может быть дело?

Problem :

Making an API call using Axios in a React Web app. However, I’m getting this error:

Axios request has been blocked by cors no 'Access-Control-Allow-Origin' header is present on the requested resource

Solution 1:

Access-Control-Allow-Origin is a response header — so in order to enable CORS — We need to add this header to the response from server.

headers: {"Access-Control-Allow-Origin": "*"} 

Solution 2:

For most cases, the better solution would be configuring the reverse proxy, so that server would be able to redirect requests from the frontend to the backend, without enabling CORS.

You can find documentation about CORS mechanism here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

Solution 3:

Server should enable the cross origin requests, not the client. To do this, We can check this nice page with implementations and configurations for multiple platforms.

Thank you for reading the article. If you face any problems, please comment below. To learn more about react, you can check The complete React developer course w/Hooks & Redux course.

Cover image for Handling CORS in Axios and Socket.io

Abhishek shah

What is CORS??

CORS stand for Cross-Origin Resource Sharing. It’s a way for the server to check if the client the server is communicating with is actually a permitted client to use the server. Before the browsers send the actual request for any operation the client sends a preflight request with a header where Origin is set to its base URL and the server replies with a Access-Control-Allow-Origin in response header.
If it’s value is a wildcard(‘*’) or the base URL matches the Origin set in the request header only then the actual request is made else you get a CORS error. This has been shown in the picture below especially focusing on the Origin values in the request header and Access-Control-Allow-Origin in the response header.

Header exchanges after a request is made

If you are getting a CORS error go to inspect mode by pressing F12 and go to network and see in the header of any file , you will find a request and response header. You can add other headers to it at CORS

Now Lets see how to handle the CORS error if you are using

  1. Axios
    You can use CORS npm package
var express = require('express')
var cors = require('cors')
var app = express()

var whitelist = ['http://example1.com', 'http://example2.com']
var corsOptions = {
  origin: function (origin, callback) {
    if (whitelist.indexOf(origin) !== -1) {
      callback(null, true)
    } else {
      callback(new Error('Not allowed by CORS'))
    }
  }
}

Enter fullscreen mode

Exit fullscreen mode

Here you can directly do an app(cors(corsOptions)) before the routers or you can add cors(corsOptions) in the (req,res,next) part.

2 Socket.io

In socket.io you have to add cors while creating io.

const io = require("socket.io")(server, {
  cors: {
    origin: "https://example.com",
    methods: ["GET", "POST"]
  }
})

Enter fullscreen mode

Exit fullscreen mode

If you have anything to add do comment and share your views.

Понравилась статья? Поделить с друзьями:
  • Axios react native network error
  • Axios post cors error
  • Axios post catch error
  • Axios json error
  • Axios interceptor error