Perfect solution to nginx cross-domain problem Request header field x-token is not allowed by Access-Control-Allow-Headers in prefligh

Access-Control-Allow-Headers

The response header Access-Control-Allow-Headers is used in the preflight request (preflight request), and lists the header information that will appear in the Access-Control-Request-Headers field of the formal request.

Simple headers, such as simple headers, Accept, Accept-Language, Content-Language, Content-Type (limited to the three MIME values ​​of application/x-www-form-urlencoded, multipart/form-data or text/plain after parsing type (excluding parameters)), they are always supported and do not need to be specifically listed in this header.

This header is required if the request contains the Access-Control-Request-Headers field.

Creator: Wu Zishan

Problems encountered:

When nginx acts as a proxy for the backend server and wants to upload files to the platform, it finds that the service has a cross-domain problem:

提示CORS :No ‘Access-Control-Allow-Origin’ header

insert image description here

First, common cross-domain configurations are configured in nginx,

add_header Access-Control-Allow-Origin * always;
add_header Access-Control-Allow-Credentials 'true';
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS' always;
add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
After restarting nginx, the problem was solved, but another cross-domain error occurred:

“Request header field x-token is not allowed by Access-Control-Allow-Headers in preflight response.”

insert image description here

Then go to the official website to search and query, and interpret the meaning of each header. . . (long time)

Finally, according to the needs of our own services, we configure a complete set of nginx configurations that perfectly solve cross-domain problems:

	add_header 'Access-Control-Allow-Origin' '*' always;
    add_header 'Access-Control-Allow-Credentials' 'true';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, PATCH, DELETE, PUT, OPTIONS';
	add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type, X-Custom-Header, Access-Control-Expose-Headers, Token, Authorization';
	add_header 'Access-Control-Allow-Headers'  '*';
    add_header 'Access-Control-Max-Age' 1728000;

Although it took a lot of time to get this, but finally solved the problem, it is still feasible.

You are welcome to refer to it, and you can also raise questions or different opinions.

Original works, please indicate the source for reprinting! !

Guess you like

Origin blog.csdn.net/Zisson_no_error/article/details/119357629