终于搞懂了 VUE 的代理和 NGINX 的代理区别了!

前端小白一枚,在开发一个 vue 项目,之前开发的时候遇到了跨域问题,通过网上冲浪自己配置了 vue 代理,美滋滋的认为一劳永逸了。 vue 代理配置如下:

在 vue.config.js 中配置
proxy: {
    '/api': {
        target: 'http://localhost:8080',
        changeOrigin: true,
        pathRewrite: {
            '^/api': ''
        }
    }
}

target: 接口域名;

changeOrigin: 如果设置为true,那么本地会虚拟一个服务端接收你的请求并代你发送该请求;

pathRewrite: 如果接口中是没有api的,那就直接置空(如上)。如果接口中有api,就需要写成{‘^/api’:‘/api’}

但是!当开完成在服务器上部署的时候,又通过网上冲浪了解到 nginx 也要配置代理,这我就迷糊了,怎么两个代理。
然后仍然要通过网上冲浪查找答案,这时我才明白,原来 vue.config.js 中配置的代理只是解决了开发环境的跨域,上线时需要配置 nginx 代理!

在 nginx.conf 中的配置
location / {
    root   /nginx/html;
    index  index.html index.htm;
    try_files $uri $uri/ /index.html;
}
location /api/ {
    proxy_next_upstream http_500 http_502 http_503 http_504 error timeout invalid_header;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass http://127.0.0.1:8123;  #代理的ip
    expires 24;
}
root /nginx/html;
location ^~/reqInfo {
    try_files $uri $uri/ /reqInfo /index.html;
}

猜你喜欢

转载自blog.csdn.net/weixin_41474364/article/details/103594622