question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

'Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.' in a POST Request

See original GitHub issue

Describe the issue I’m try to consume an POST method from my API (Web API C#), I have two problems, the first was that Axios get the error 'Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.' and this was solved add to the controller api a default code for Options:

[HttpOptions]
public IHttpActionResult Options()
{
    return Ok();
}

And I use the code to consume:

let data = {
       Nit_ID: '899999284',
       UserName: 'sasfdm',
       Password: btoa('123456789'),
       Public_IP: '123.456.789.123',
       Private_IP: '987.654.321.987'
 };
 //
let resultApi = await axios.post(
           "https://localhost:44377/api/usuario",
           data
 };

Now, I want to send a header and I get the same error Access to XMLHttpRequest at 'https://localhost:44377/api/usuario/verifydoublefactorcode' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.

Example Code I get the error when I use the next sintax:

let data = {
       Nit_ID: "899999284",
       UserName: "sasfdm",
       Code: "1eb16ac5"
};
console.log(localStorage.getItem("DoubleFactorToken"));
let headers = {
       'Authorization': localStorage.getItem("DoubleFactorToken")
};
let resultApi = await axios.post(
     this.apiSeguridad + "usuario/verifydoublefactorcode",
     data,
     {
         headers: headers
     }
);

But If I use Ajax to send the request, I get the answer that I wait:

let data = {
       Nit_ID: "899999284",
       UserName: "sasfdm",
       Code: "1eb16ac5"
};
console.log(localStorage.getItem("DoubleFactorToken"));
let headers = {
     Authorization: localStorage.getItem("DoubleFactorToken")
};
let resultApi = await $.ajax({
          cache: false,
          type: "POST",
          url:  "https://localhost:44377/api/usuario/verifydoublefactorcode",
          headers: headers,
          data: data
 });
console.log(resultAPI);

image

Expected behavior, if applicable I used Posman to send the request, and I wait the next answer:

{
    "Nit_ID": "899999284",
    "UserName": "sasfdm",
    "FullName": "Fabian Dario Montoya",
    "CorreoEncrypt": null,
    "Token": null,
    "Option": 1,
    "Error": true,
    "Mensaje": "El código de verificación no coincide con el autorizado. Favor validar."
}

image

Environment:

  • Axios Version 0.19.0
  • Vue-Axios: 2.1.4
  • OS: [Win 10 v. 1903]
  • Browser: Google Chrome
  • Browser Version 76.0.3809.87
  • Additional Library Versions: Vue: 3.9.3

Additional context/Screenshots Add any other context about the problem here. If applicable, add screenshots to help explain.

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:5

github_iconTop GitHub Comments

12reactions
asad041commented, Nov 1, 2019

You must indicate what type of Access-Control-Allow-Headers are acceptable at your server end. In your case it is Authorization so it would be like this;

server-side (PHP):

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: Authorization");

client side:

const headers = { "Authorization" : `Bearer ${token}` };
const response = await axios.get(url, { headers: headers });

For the cross-origin policy spec about this see here

1reaction
sergxcommented, Sep 26, 2019

This worked out for me:

axios({
  method: 'post',
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  url: 'http://my-api-site.ru/ajax.php',
  data: { user_data : true }
}).then(function (response) {
  console.log(response.data);
});

And on server side (PHP):

header('Access-Control-Allow-Origin: *');
Read more comments on GitHub >

github_iconTop Results From Across the Web

Request header field Access-Control-Allow-Headers is not ...
Notice the Authorization value for the Access-Control-Allow-Headers key. I was missing the Authorization value, this config solves my issue. Share.
Read more >
Request header field content-type is ... - Netlify Support Forums
My netlify function has these headers set up: const headers = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': ...
Read more >
Access-Control-Allow-Headers - HTTP - MDN Web Docs
If the CORS request indicated by the preflight request is authorized, the server will respond to the preflight request with a message that ......
Read more >
CORS error: Request header field Authorization is not allowed ...
The CORS error "Request header field Access-Control-Allow-Headers is not allowed by Access-Control-Allow-Headers in preflight response" occurs when your browser ...
Read more >
Request header field authorization is ... - Okta Developer forums
It never gets to send the request because it won't allow the authorization header, so it fails in CORS pre-flight. Hekmil October 21,...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found