lua+nginx做代理请求时,返回非200状态码内容时会提示跨域

今天解决错误主要是跨域的问题,这个跨域在nginx上配置add_header什么的都不够,遇到非200的请求就会出现跨域问题,这个是因为在nginx官方文档写了, add_header只有在 200, 201 (1.3.10), 204, 206, 301, 302, 303, 304, 307 (1.1.16, 1.0.13), or 308 (1.13.0). 才会生效,其他的状态码要生效的话,就得添加 always这个参数,官网文档是:http://nginx.org/en/docs/http/ngx_http_headers_module.html , ,如果在nginx上添加了这个,就不需要在lua上做操作了。

add_header name value [always];

如果就想在lua做操作,在lua上对后端服务器返回非200的请求添加跨域配置。 跨域问题详情可以参考这篇 https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS

前端产生的现象是:

No 'Access-Control-Allow-Origin' header is present on the requested resource.

lua日志打印的如下:

2020/12/04 20:30:06 [error] 8643#0: *39 [lua] front_proxy.lua:119: do_request(): 开始请求,url:http://pisces.xxx.com.cn/403 , method:GET, body: headers:accept:*/*,Host:pisces.xxx.com.cn,content-type:application/x-www-form-urlencoded,user-agent:Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Mobile Safari/537.36,, client: 172.18.3.101, server: ljf-daili.xxx.com, request: "GET /?url=http://pisces.xxx.com.cn/403 HTTP/1.1", host: "ljf-daili.xxx.com", referrer: "http://pisces.xxx.com.cn/"
2020/12/04 20:30:06 [error] 8643#0: *39 [lua] front_proxy.lua:121: do_request(): no body, client: 172.18.3.101, server: ljf-daili.xxx.com, request: "GET /?url=http://pisces.xxx.com.cn/403 HTTP/1.1", host: "ljf-daili.xxx.com", referrer: "http://pisces.xxx.com.cn/"
2020/12/04 20:30:06 [error] 8643#0: *39 [lua] front_proxy.lua:144: do_request(): type of res.body:string, client: 172.18.3.101, server: ljf-daili.xxx.com, request: "GET /?url=http://pisces.xxx.com.cn/403 HTTP/1.1", host: "ljf-daili.xxx.com", referrer: "http://pisces.xxx.com.cn/"
2020/12/04 20:30:06 [error] 8643#0: *39 [lua] front_proxy.lua:160: do_request(): 响应状态码,ngx.status:403, client: 172.18.3.101, server: ljf-daili.xxx.com, request: "GET /?url=http://pisces.xxx.com.cn/403 HTTP/1.1", host: "ljf-daili.xxx.com", referrer: "http://pisces.xxx.com.cn/"
2020/12/04 20:30:06 [error] 8643#0: *39 [lua] front_proxy.lua:161: do_request(): 响应结果 , ngx.print:<!doctype html>
......

解决办法

在lua代码里面添加以下代码,这样在返回非200状态码请求的时候,就不会再显示跨域问题了。

....省去代理的代码,以下为收到代理结果后的代码
ngx.status = res.status
if ngx.status ~= 200 then
    ngx.header["Access-Control-Allow-Origin"] = "*"  --  添加头信息,允许跨域
end

ngx.print(result)
return ngx.exit(ngx.status)

这样浏览器就不会再说跨域问题了

posted @ 2020-12-08 14:56  温柔易淡  阅读(1412)  评论(0编辑  收藏  举报