宝塔解决跨域

618 阅读2分钟

问题:使用前后端分离开发项目,后端使用tp5,前端使用vue,已给后端tp5的入口文件配置跨域操作,但前端无法访问后端静态资源文件,因为访问静态资源文件不经过入口文件public目录下的index.php,所以本人就反其道而行之,直接在服务器上配置跨域

1.我使用的服务器是基本linux系统的宝塔面板,首先找到自己后端服务的站点,点击设置,找到配置文件,添加以下代码,具体的内容可以根据自己的需求更改内容

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'; 

修改结果如下图所示,点击保存后即可,记住从启nginx

Snipaste_2023-10-24_15-01-40.png

2.你以为这就结束了,其实的确结束了,但如果你和我一样,之前在代码里面已经进行过跨域操作,就会出现以下错误

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

非常感谢原文作者,我也是处理了了很久,看到这篇文章才处理的,开始代码里解决了api的跨域,导致客户端不仅图片资源拿不到了,接口也报上面那个错误,当时没注意看错误原因,以为还是跨域。结果在作者的文章中仔细看了一下报错,原来是解决跨域只能存在一个。我就删除了代码里面的跨域,就完美解决了。非常感谢.

3.如果你的响应码不止200,需要把上面的第一句话,换成下面的这个,要不然除了200其它都要跨域

    add_header Access-Control-Allow-Origin * always;

4.hyperf这种暂用端口的项目如何配置跨域


upstream hyperf_backend {
    # Hyperf HTTP Server 的 IP 及 端口
    server ********:9501;
}

server
{
    listen 9502;  # 监听的端口
    server_name *******;  # 服务的ip
    location / {
        proxy_pass http://hyperf_backend;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    add_header Access-Control-Allow-Origin *;
    add_header Access-Control-Allow-Methods 'POST,PUT,GET,OPTIONS,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,packname,lang';
    }
  }

原文链接:blog.csdn.net/weixin_4357…

小伙伴们!这样就完成了哦! QQ学习交流群:842167453,欢迎小伙伴加入一起学习。