Home >Web Front-end >JS Tutorial >Why is my \'Access-Control-Allow-Origin\' header not allowed in \'Access-Control-Allow-Headers\' when sending files with a POST request in Angular?
Issue: Cross-Origin Request Errors with Headers
When attempting to send files with a POST request, developers may encounter an error indicating that a specific request header is not allowed by the Access-Control-Allow-Headers response header.
To resolve this issue, the developer added the following headers to the request:
"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"
However, this resulted in a new error stating that the "Access-Control-Allow-Origin" header is not allowed by the "Access-Control-Allow-Headers" header.
Solution: Header Restrictions and Default Content Type
For cross-origin requests, browsers will send a preflight OPTIONS request if the content type is not set to one of three specific types: "application/x-www-form-urlencoded", "multipart/form-data", or "text/plain".
By default, Angular sets the content type to "application/json", which is not one of the acceptable types for cross-origin requests. This triggers the preflight OPTIONS request, which is then rejected due to the restrictions on the "Access-Control-Allow-Headers" header.
To resolve this issue, the developer can overwrite the default content type in Angular or allow the "Access-Control-Allow-Headers" header on the server side.
An Angular sample that overwrites the default header:
$http.post(url, data, { headers : { 'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8' } });
The above is the detailed content of Why is my \'Access-Control-Allow-Origin\' header not allowed in \'Access-Control-Allow-Headers\' when sending files with a POST request in Angular?. For more information, please follow other related articles on the PHP Chinese website!