'Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.' in a POST Request
See original GitHub issueDescribe 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);
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."
}
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:
- Created 4 years ago
- Comments:5
Top GitHub Comments
You must indicate what type of
Access-Control-Allow-Headers
are acceptable at your server end. In your case it isAuthorization
so it would be like this;server-side (PHP):
client side:
For the cross-origin policy spec about this see here
This worked out for me:
And on server side (PHP):