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
In Asp Net Core, to quickly get it working for development; in Startup.cs
, Configure method
add
app.UseCors(options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
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
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");
}
}
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>
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();
});
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.
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.