lua实现跨域请求(Nginx)
基于工作需要,致力于成为合格前端工程师,对于后端的东西当然也得会点。
web 服务器是Nginx,写完nginx+lua的token令牌系统后,当然是首要解决跨域的问题,否则web端请求就会麻烦了。
写这个lua跨域处理目标就是让web端 ajax请求跟移动端一样简单。
一、编写脚本
1.新建handle_cors.lua脚本文件
ngx.header["Access-Control-Allow-Origin"] = "*"
ngx.header["Access-Control-Allow-Headers"] = "DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range, userid, agent, brandid, language, token"
if ngx.var.request_method == "OPTIONS" then
ngx.header["Access-Control-Max-Age"] = "1728000"
ngx.header["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS, PUT, DELETE"
ngx.header["Content-Length"] = "0"
ngx.header["Content-Type"] = "text/plain, charset=utf-8"
end
ps:
1. “Access-Control-Allow-Headers”想要跨域请求通过的请求头信息,已有些过滤功能
2. “Access-Control-Allow-Methods”想要跨域的请求方式
二、配置Nginx
1.配置nginx.conf信息
在server里对需要跨域的url添加
location / {
# CORS handle_cors.lua path:"lua/handlefile/handle_cors.lua"
header_filter_by_lua_file lua/handlefile/handle_cors.lua;
if ($request_method = 'OPTIONS') {
return 204;
}
proxy_pass http://xxx.xx;
}
End…