今天解決錯誤主要是跨域的問題,這個跨域在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)
這樣瀏覽器就不會再說跨域問題了