nginx php 403 js,Nginx 跨域 add_header 403状态下无效

WEB前后端分离的应用,前端跨域请求API服务器。这是前要。

当然,一开始直接上,js报报一堆 No "Access-Control-Allow-Origin" header 的错误,那很明显了,nginx允许跨域的关键, 使用add_header函数添加头即可。整理代码如下,添加在 location 节点

add_header "Access-Control-Allow-Origin" "*";

add_header "Access-Control-Max-Age" "1000";

add_header "Access-Control-Allow-Methods" "POST, GET, OPTIONS, DELETE, PUT";

add_header "Access-Control-Allow-Headers" "x-requested-with, Content-Type, origin, authorization, accept, client-security-token";

前端妹子测试,一切安好。

当然啦,问题肯定要来了,不然不在这里废话了。

一个表单验证,服务器返回422,并提示相应的错误信息。前端是死活无法显示。js报错如下:

Response to preflight request doesn"t pass access control check:

No "Access-Control-Allow-Origin" header is present on the requested resource. Origin "http://10.10.20.154:3000" is therefore not allowed access.

If an opaque response serves your needs, set the request"s mode to "no-cors" to fetch the resource with CORS disabled.

也很好理解,没有跨域权限嘛。但是不对嘛,nginx 明明已经配置了。

仔细检查 POST 的记录,发现 Response Headers 没有 Access-Control那一堆。当然了,解决方法是有的,官方也给出了解释。只有在 状态码是 200,201,204,302.....的情况下,才有效。除非你使用always关键字。

107335

add_header解释

最终nginx配置成下边的样子,解决问题。

add_header "Access-Control-Allow-Origin" "*" always;

add_header "Access-Control-Max-Age" "1000" always;

add_header "Access-Control-Allow-Methods" "POST, GET, OPTIONS, DELETE, PUT" always;

add_header "Access-Control-Allow-Headers" "x-requested-with, Content-Type, origin, authorization, accept, client-security-token" always;

Apache很好,在应用根目录下的 .htaccess 文件,贴入下内容即可:

Header always set Access-Control-Allow-Origin *

Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"

Header always set Access-Control-Max-Age "1000"

Header always set Access-Control-Allow-Headers "x-requested-with, origin, authorization, accept, client-security-token"

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值