Home > Web Front-end > JS Tutorial > body text

CORS Error: Why Does My Server Reject \'Content-Type\' in the Preflight Request?

Patricia Arquette
Release: 2024-10-28 14:21:02
Original
445 people have browsed it

CORS Error: Why Does My Server Reject

CORS Error: Modifying Allowed Headers

When attempting to perform a POST request with file uploads, the browser often encounters the error: "Request header field Content-Type is not allowed by Access-Control-Allow-Headers."

Root Cause:

This error occurs because browsers preflight requests for cross-origin requests with non-standard content types like "multipart/form-data" by sending an OPTIONS request. The OPTIONS request checks if the server allows specific request headers that are not included in the standard HTTP set.

Initial Attempted Solution:

To resolve this issue, the developer initially tried adding the following headers to the POST 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"
Copy after login

Subsequent Error:

However, this resulted in a new error: "Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers."

Resolution:

The issue arises because the server must allow the "Content-Type" header in the "Access-Control-Allow-Headers" configuration. Browsers send a preflight OPTIONS request with the "Content-Type" header, and if the server does not allow it, the CORS request will fail.

To resolve this error, the developer should either overwrite Angular's default "application/json" content type or allow "Content-Type" in the server's Access-Control-Allow-Headers configuration.

Angular Code Sample:

To overwrite the default header in Angular, the following code can be used:

<code class="typescript">$http.post(url, data, {
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    }
});</code>
Copy after login

The above is the detailed content of CORS Error: Why Does My Server Reject \'Content-Type\' in the Preflight Request?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!