Request header field Access-Control-Allow-Headers is not allowed by Access-Control-Allow-Headers
Asked Answered
O

17

281

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?

Octagon answered 8/9, 2014 at 15:3 Comment(1)
These headers are sent from server to browser so the browser can decide if the JS is allowed to parse the response. Adding them to the request has not value.Filippa
A
232

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.

Ameliaamelie answered 8/9, 2014 at 15:8 Comment(12)
How do I set the headers in the backend?Octagon
@user3194367: Depends on your backend.Capella
I guess I'll have to talk to my server guy.Octagon
response.addHeader("Access-Control-Allow-Headers", "yourKey");Seligman
@Seligman yourKey is what? Content-Type?Mosquito
@Mosquito , Try this : headers = req.headers['access-control-request-headers']; if (headers) res.setHeader('Access-Control-Allow-Headers', headers);Seligman
@Seligman I have tried this configure in nginx:add_header Access-Control-Allow-Headers X-Requested-With,Content-Type; and just need append Content-Type, and it works.Mosquito
As witnessed by multiple answers for Access-Control-Request-Headers, there are clearly differences due to different environments. What worked for me was to get access to the request object and dump the values for the headers, but specifically the header value for "Access-Control-Request-Headers". Then, copy/paste this into your response.setHeader("Access-Control-Allow-Headers", "{paste here}")Performative
example please!Guardrail
so this is a browser issue right? Meaning I can hit ours in a mocha integration test locally but I get this error when running the same code in the browserGodson
Remove Access-Control-Allow-Origin field from the request header.Ephrem
This doesn't work for me. I added that header header('Access-Control-Allow-Headers: Content-Type'); and I still get precisely the same CORS error.Schnurr
T
296

I had the same problem. In the jQuery documentation I found:

For cross-domain requests, setting the content type to anything other than application/x-www-form-urlencoded, multipart/form-data, or text/plain will trigger the browser to send a preflight OPTIONS request to the server.

So though the server allows cross origin request but does not allow Access-Control-Allow-Headers , it will throw errors. By default angular content type is application/json, which is trying to send a OPTION request. Try to overwrite angular default header or allow Access-Control-Allow-Headers in server end. Here is an angular sample:

$http.post(url, data, {
    headers : {
        'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
    }
});
Transformation answered 31/5, 2015 at 6:1 Comment(11)
This should be an accepted answer, much more informative than the other one!Choirboy
I would like multipart/form-data because I want to uplaod somethingClave
and how to allow it in the server, for example using PHP? what header?Monster
@Monster : in php there is functiion name header() to set header. see the header name from below answersTransformation
In Angular 2, do something like this: var headers:Headers = new Headers(); headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); var options = {headers:headers}; this.http.post(this.presenseURL, data, options)...Daric
or allow Access-Control-Allow-Headers in server end how?Scrutator
@omar it depends on what server platform you using. if java there is example on other answers if php then there is a function name header to set header of the responseTransformation
@Transformation Awesome! Thanks for that! Solved a similar error I was encountering using Axios v18 in React 16.4.2.Pun
Finally, after two days of research. I have got no words to thank you!Oliverolivera
After searching for hours! this only worked in react as well using axios even in localhost Kudos! Stop those "Access-Control-Allow-Origin" : "*" !!!Partner
headers : { 'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8' }Contrayerva
A
232

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.

Ameliaamelie answered 8/9, 2014 at 15:8 Comment(12)
How do I set the headers in the backend?Octagon
@user3194367: Depends on your backend.Capella
I guess I'll have to talk to my server guy.Octagon
response.addHeader("Access-Control-Allow-Headers", "yourKey");Seligman
@Seligman yourKey is what? Content-Type?Mosquito
@Mosquito , Try this : headers = req.headers['access-control-request-headers']; if (headers) res.setHeader('Access-Control-Allow-Headers', headers);Seligman
@Seligman I have tried this configure in nginx:add_header Access-Control-Allow-Headers X-Requested-With,Content-Type; and just need append Content-Type, and it works.Mosquito
As witnessed by multiple answers for Access-Control-Request-Headers, there are clearly differences due to different environments. What worked for me was to get access to the request object and dump the values for the headers, but specifically the header value for "Access-Control-Request-Headers". Then, copy/paste this into your response.setHeader("Access-Control-Allow-Headers", "{paste here}")Performative
example please!Guardrail
so this is a browser issue right? Meaning I can hit ours in a mocha integration test locally but I get this error when running the same code in the browserGodson
Remove Access-Control-Allow-Origin field from the request header.Ephrem
This doesn't work for me. I added that header header('Access-Control-Allow-Headers: Content-Type'); and I still get precisely the same CORS error.Schnurr
S
58

If that helps anyone, (even if this is kind of poor as we must only allow this for dev purpose) here is a Java solution as I encountered the same issue. [Edit] Do not use the wild card * as it is a bad solution, use localhost if you really need to have something working locally.

public class SimpleCORSFilter implements Filter {

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletResponse response = (HttpServletResponse) res;
    response.setHeader("Access-Control-Allow-Origin", "my-authorized-proxy-or-domain");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
    chain.doFilter(req, res);
}

public void init(FilterConfig filterConfig) {}

public void destroy() {}

}
Spiritualize answered 25/11, 2015 at 3:5 Comment(3)
As witnessed by multiple answers for Access-Control-Request-Headers, there are clearly differences due to different environments. What worked for me was to get access to the request object and dump the values for the headers, but specifically the header value for "Access-Control-Request-Headers". Then, copy/paste this into your response.setHeader("Access-Control-Allow-Headers", "{paste here}"); I am also using Java, but I required additional values and some mentioned in this answer I didn't need.Performative
This was a partial (and as said, poor) solution to help people and share clues one year back. I dont see the point of down voting, but well this is your liberty. The idea is to allow the headers on the server side so when an OPTION request is posted, the client / the browser knows which headers are allowed. I acknowledge there is a bit of confusion, my CORS filter has changed a lot since then. As a better practice, Access-Control-Allow-Origin should never be *; in my implementation, it's set by a property.Spiritualize
The solution has been edited to include best practicesSpiritualize
D
23

You can activate the proper header in PHP with this:

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, X-Requested-With");
Donahue answered 12/7, 2018 at 14:21 Comment(3)
Please describe how your answer is any different to the other answers. Just posting some code is not very helpful.Hesperides
You are a rock-star, the rest of the answers delve into the technical side. Yours fixes my issue, by specifying the methods that should be allowed as well!Antenatal
@DanielZA although I understand what you mean by "the other answers delve into the technical side" as you just want to make yout code run, SO is meant to delve into the technical side of things as you should know why things are working not just how to make then work. Do not encorage this behavior when commenting on solutions...Inconformity
C
19

The server (that the POST request is sent to) needs to include the Content-Type header in its response.

Here's a list of typical headers to include, including one custom "X_ACCESS_TOKEN" header:

"X-ACCESS_TOKEN", "Access-Control-Allow-Origin", "Authorization", "Origin", "x-requested-with", "Content-Type", "Content-Range", "Content-Disposition", "Content-Description"

That's what your http server guy needs to configure for the web server that you're sending your requests to.

You may also want to ask your server guy to expose the "Content-Length" header.

He'll recognize this as a Cross-Origin Resource Sharing (CORS) request and should understand the implications of making those server configurations.

For details see:

Corelation answered 23/2, 2015 at 15:29 Comment(0)
W
8

The following works for me with nodejs:

xServer.use(function(req, res, next) {
  res.setHeader("Access-Control-Allow-Origin", 'http://localhost:8080');
  res.setHeader('Access-Control-Allow-Methods', 'POST,GET,OPTIONS,PUT,DELETE');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type,Accept');

  next();
});
Worsham answered 16/4, 2016 at 16:29 Comment(2)
does the order of the Access-Control-Allow-Methods matter?Dermatitis
@vini, i think it does not matter.Springy
K
8

If you are using localhost and PHP set to this to solve the issue:

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Content-Type'); 

From your front-end use:

{headers: {"Content-Type": "application/json"}}

and boom no more issues from localhost!

Kan answered 15/3, 2020 at 0:29 Comment(1)
TY this is the correct way to fix it on PHP!Mentalism
S
5

In Asp Net Core, to quickly get it working for development; in Startup.cs, Configure method add

app.UseCors(options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
Sanbo answered 3/10, 2019 at 17:30 Comment(0)
H
4

The headers you are trying to set are response headers. They have to be provided, in the response, by the server you are making the request to.

They have no place being set on the client. It would be pointless having a means to grant permissions if they could be granted by the site that wanted permission instead of the site that owned the data.

Henriquez answered 8/9, 2014 at 15:5 Comment(3)
How do I set the headers in the backend?Octagon
@Octagon — It depends on your backend. I don't know what HTTP server or programming language you are making the request to.Henriquez
I guess I'll have to talk to my server guy.Octagon
B
4

If anyone experiences this problem with an express server, add the following middleware

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});
Baculiform answered 23/10, 2016 at 14:8 Comment(0)
P
3

In my case, I'm receiving several parameters as @HeaderParam into a web service method.

These parameters MUST be declared in your CORS filter that way:

@Provider
public class CORSFilter implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {

        MultivaluedMap<String, Object> headers = responseContext.getHeaders();

        headers.add("Access-Control-Allow-Origin", "*");
        ...
        headers.add("Access-Control-Allow-Headers", 
        /*
         * name of the @HeaderParam("name") must be declared here (raw String):
         */
        "name", ...);
        headers.add("Access-Control-Allow-Credentials", "true");
        headers.add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");   
    }
}
Polytypic answered 10/8, 2016 at 8:33 Comment(0)
H
3

if you testing some javascript requests for ionic2 or angularjs 2 , in your chrome on pc or mac , then be sure that you install CORS plugin for chrome browser to allow cross origin .

mayba get requests will work without needing that , but post and puts and delete will need you to install cors plugin for testing to go without problems , that definitley not cool , but i do not know how people do it without CORS plugin .

and also be sure the json response is not returning 400 by some json status

Hephzipah answered 8/11, 2016 at 13:17 Comment(0)
P
3

this is backend problem. if use sails api on backend change cors.js and add your filed here

module.exports.cors = {
  allRoutes: true,
  origin: '*',
  credentials: true,
  methods: 'GET, POST, PUT, DELETE, OPTIONS, HEAD',
  headers: 'Origin, X-Requested-With, Content-Type, Accept, Engaged-Auth-Token'
};
Pacheco answered 17/12, 2016 at 23:41 Comment(0)
X
3

Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers error means that Access-Control-Allow-Origin field of HTTP header is not handled or allowed by response. Remove Access-Control-Allow-Origin field from the request header.

Xerophagy answered 12/4, 2018 at 19:44 Comment(0)
P
1

For me, Added the following to my server's web.config file:

<system.webServer>
    <httpProtocol>
        <customHeaders>
            <add name="Access-Control-Allow-Origin" value="https://other.domain.com" />
            <add name="Access-Control-Allow-Methods" value="GET,POST,OPTIONS,PUT,DELETE" />
            <add name="Access-Control-Allow-Headers" value="Content-Type,X-Requested-With" />
        </customHeaders>
    </httpProtocol>
<system.webServer>
Predetermine answered 4/10, 2020 at 17:33 Comment(1)
what is exactly kind of app using this config file? Is angularjs can handle this case using the web config?Thrombophlebitis
I
0

For me I had wildcard "*" Access-Control-Allow-Headers in web.config:

<add name="Access-Control-Allow-Headers" value="*" />

This solution works for most navigators but not for Safari or IE

Browser compatibility wildcard Access-Control-Allow-Headers

It turned out the solution was to add manually all the custom header to the web.config:

<system.webServer>
    <httpProtocol>
        <customHeaders>
            <add name="Access-Control-Allow-Origin" value="https://somedomain.com" />
            <add name="Access-Control-Allow-Methods" value="GET,POST,OPTIONS,PUT,DELETE" />
            <add name="Access-Control-Allow-Headers" value="custom-header1, custome-header2, custome-header3" />
        </customHeaders>
    </httpProtocol>
<system.webServer>
Impulsion answered 12/3, 2021 at 20:38 Comment(0)
R
0

Fix for me running Angular on a different port to API:

I just needed to add WithHeaders with a wildcard "*" to the Cors Options in the webapi builder.

builder.Services.AddCors(options =>
{

    options.AddPolicy(myAllowSpecificOrigins, policy => {
        policy.WithOrigins("https://localhost:4200", "http://localhost:4200");
        policy.WithHeaders("*"); 
    });
});
Reply answered 29/3, 2023 at 13:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.