问题
I'm encountering a problem where axios doesn't seem to send custom headers with my requests.
I'm using it like this:
axios({
method: 'get',
url: 'www.my-url.com',
headers: { 'Custom-Header': 'my-custom-value' }
})
However, looking at the actual request that is sent to the server, the custom header doesn't seem to be anywhere.
REQUEST HEADERS:
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: es-ES,es;q=0.9
Access-Control-Request-Headers: custom-header
Access-Control-Request-Method: GET
Connection: keep-alive
Host: my-url.com
I suspect it might be a CORS problem (the response headers don't include Custom-Header in Access-Control-Allow-Headers), but I would like to make sure before contacting the API owners about the matter.
回答1:
Ok. so your case is preflight request. when client tries to send a custom header, server needs to verify that it accepts that header.
so in that case, a preflight options request is sent with header Access-Control-Request-Headers. if server responds that it will accept the custom header. then actual request will be sent.
in your case server response header - access-control-allow-headers does not contains your custom header name. thats why it failed.
Note: the actual POST request does not include the Access-Control-Request-* headers; they are needed only for the OPTIONS request.Read this article for more explanation - cors - options call
回答2:
Your axios request is correct. You need to allow your custom headers on server side. If you have your api in php then this code will work for you.
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, HEAD");
header("Access-Control-Allow-Headers: Content-Type, Custom-Header");
Once you will allow your custom headers on server side, your axios requests will start working fine.
来源:https://stackoverflow.com/questions/50603715/axios-not-sending-custom-headers-in-request-possible-cors-issue