I’m trying to send files to my server with a post request, but when it sends it causes the error:
Request header field Content-Type is not allowed by Access-Control-Allow-Headers.
So I googled the error and added the headers:
$http.post($rootScope.URL, {params: arguments}, {headers: { "Access-Control-Allow-Origin" : "*", "Access-Control-Allow-Methods" : "GET,POST,PUT,DELETE,OPTIONS", "Access-Control-Allow-Headers": "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With" }
Then I get the error:
Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers
So I googled that and the only similar question I could find was provided a half answer then closed as off topic. What headers am I supposed to add/remove?
Advertisement
Answer
The server (that the POST request is sent to) needs to include the Access-Control-Allow-Headers
header (etc) in its response. Putting them in your request from the client has no effect. You should remove the ‘Access-Control-Allow-…’ headers from your POST request.
This is because it is up to the server to specify that it accepts cross-origin requests (and that it permits the Content-Type
request header, and so on) – the client cannot decide for itself that a given server should allow CORS.
The requestor (web browser) may ‘preflight’ test what the server’s Same Origin Policy is by sending an ‘OPTIONS’ request (ie not the ‘POST’ or ‘GET’ request you intend). If the response to the ‘OPTIONS’ request contains ‘Access-Control-Allow-…’ headers that permit the headers, origin, or methods your request is using, then the requester/browser will send your ‘POST’ or ‘GET’ request.
(obscure note:) The Access-Control-Allow-… have the value ‘‘ rather than listing the specific origin, headers, or methods allowed. However, and old Android WebView client I was using didn’t honor the ‘‘ wildcard and needed the specific headers listed in the Access-Control-Allow-Headers header in the response to the OPTIONS request.