配置OpenResty的跨域
时间: 2024-04-23 12:19:59 浏览: 390
要配置OpenResty实现跨域,可以按照以下步骤进行操作:
1.OpenResty的配置文件中,找到`http`块,并在其中添加以下内容:
```
http {
...
lua_shared_dict cors 10m;
init_by_lua_block {
local cors = require "cors"
cors.init({
origin = {"*"}, -- 允许的来源,可以设置为具体的域名或IP地址
methods = {"GET", "POST", "PUT", "DELETE"}, -- 允许的HTTP方法
headers = {"Content-Type"}, -- 允许的请求头
exposed_headers = {}, -- 允许暴露的响应头
max_age = 3600, -- 预检请求的有效期
credentials = false, -- 是否允许发送Cookie
options_passthrough = false -- 是否直接通过OPTIONS请求
})
}
...
}
```
2. 在OpenResty的配置文件中,找到`server`块,并在需要跨域的location中添加以下内容:
```
location /api {
...
access_by_lua_block {
local cors = require "cors"
cors.process()
}
...
}
```
其中,`/api`是需要跨域的接口路径,根据实际情况进行修改。
3. 在OpenResty的配置文件中,找到`lua_package_path`配置项,并添加以下内容:
```
lua_package_path "/path/to/lua-resty-cors/lib/?.lua;;";
```
其中,`/path/to/lua-resty-cors`是lua-resty-cors库的路径,需要根据实际情况进行修改。
4. 重启OpenResty服务,使配置生效。
这样,就完成了OpenResty的跨域配置。
阅读全文