user6830922
user6830922

Reputation:

How to send CORS request from React?

I have problem with sending CORS request with token in header. Fetch code:

fetchApi() {
    fetch('http://some-link.com',
    {
        headers: {
          'Accept': 'application/json',
          'auth-token': 'xxxxxxxxx'
        },
        method: "GET"
    }).then(response => response.json())
        .then(function(response){
            this.setState({hits:response});
        }).catch(function(error) { console.log(error); });

        console.log(this.state.hits);
};

Console log: Access to fetch at 'http://some-link.com' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field auth-token is not allowed by Access-Control-Allow-Headers in preflight response.

Network request log:

General
Request URL: http://some-link.com
Request Method: OPTIONS
Status Code: 200 OK
Remote Address: some_ip:80
Referrer Policy: no-referrer-when-downgrade

Response Headers
Access-Control-Allow-Headers: origin, x-requested-with, content-type, auth_token
Access-Control-Allow-Methods: POST, GET, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin: *
Cache-Control: no-cache, private
Connection: Keep-Alive
Content-Length: 8
Content-Type: application/json
Date: Tue, 13 Nov 2018 13:30:35 GMT
Keep-Alive: timeout=5, max=100
Server: Apache/2.4.10 (Debian)

Request Headers
Provisional headers are shown
Access-Control-Request-Headers: auth-token
Access-Control-Request-Method: GET
Origin: http://localhost:3000
Referer: http://localhost:3000/
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36

Any ideas what might be wrong?

Upvotes: 2

Views: 1391

Answers (1)

Rupert
Rupert

Reputation: 1639

You have to change the server settings to allow the header "auth-token".

Once you do this, your request will work.

You are currently allowing "auth_token", not "auth-token".

Alternatively, change the header name in the frontend like so:

 headers: {
   'Accept': 'application/json',
   'auth_token': 'xxxxxxxxx'
 }

Upvotes: 1

Related Questions