完美解决nginx跨域问题Request header field x-token is not allowed by Access-Control-Allow-Headers in prefligh

Access-Control-Allow-Headers

响应首部 Access-Control-Allow-Headers 用于 preflight request (预检请求)中,列出了将会在正式请求的 Access-Control-Request-Headers 字段中出现的首部信息。

简单首部,如 simple headers、Accept、Accept-Language、Content-Language、Content-Type (只限于解析后的值为 application/x-www-form-urlencoded、multipart/form-data 或 text/plain 三种MIME类型(不包括参数)),它们始终是被支持的,不需要在这个首部特意列出。

如果请求中含有 Access-Control-Request-Headers 字段,那么这个首部是必要的。

创作者:吴仔汕

遇到的问题:

nginx代理后端服务器,想要去上传文件至的平台时,却发现服务出现了跨域问题:

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

在这里插入图片描述

首先、在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';
重启nginx后,问题得到解决,但是又出现另一个跨域的报错:

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

在这里插入图片描述

然后去官网里面搜索查询,解读各header的含义。。。(很久)

最后自己服务的需求配置了一套完美解决跨域问题的全套nginx配置:

	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;

尽管花了一大堆时间去弄这个,但最后还是解决了这个问题,还是可行的。

欢迎大家参考,还可以提出疑问或者不同看法噢。

原创作品,转载请标明出处!!

猜你喜欢

转载自blog.csdn.net/Zisson_no_error/article/details/119357629
今日推荐