欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

宝塔 nginx配置跨域

程序员文章站 2022-07-10 12:44:32
...

点击相关网站的“设置”按钮,弹出弹窗如下图

location / {} 中添加一下代码

	add_header Access-Control-Allow-Origin '*';
    add_header Access-Control-Allow-Methods 'POST,PUT,GET,DELETE';
    add_header Access-Control-Allow-Headers 'version, access-token, user-token, Accept, apiAuth, User-Agent, Keep-Alive, Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With'; 

    if ($request_method = 'OPTIONS') {
        return 204;
    }

Access-Control-Allow-Origin
Access-Control-Allow-Methods
Access-Control-Allow-Headers
这三项的具体内容可以根据自身需求修改

我的项目最终的结果图如下
宝塔 nginx配置跨域

注意!!在代码中不要进行跨域操作

如果报错信息为

The ‘Access-Control-Allow-Origin’ header contains multiple values’*, *’, but only one is allowed.

则说明你在代码中有跨域的中间件或者类似以下代码,请删除!!!

header('Access-Control-Allow-Origin:*');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS,PATCH');
header('Access-Control-Allow-Credentials:true');;