Home >Web Front-end >JS Tutorial >CORS Error: Why Does My Server Reject \'Content-Type\' in the Preflight Request?

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

Patricia Arquette
Patricia ArquetteOriginal
2024-10-28 14:21:02531browse

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"

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>

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!

Statement:
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