Vue代理解决生产环境跨域问题 部署必备干货

当我们前端要调用跨域接口时,我们需要用代理解决跨域问题,比如Vue的代理配置proxy,但是当Vue项目打包成静态文件时,他的代理也就失灵了,因为代理的前提是本地必须有service,本章讲一下生产环境的Vue项目如何做代理。

本章我们从两方面讲解Vue解决跨域的方案,一种是本地开发环境,另一种是生产环境(nginx解决vue跨域问题)

1.Vue本地(开发环境)解决跨域流程如下

(1)打开config/index.js,在proxyTable中添写如下代码:

proxyTable: { 
  '/api': {  //使用"/api"来代替"http://f.apiplus.c" 
    target: 'http://f.apiplus.cn', //源地址 
    changeOrigin: true, //改变源 
    pathRewrite: { 
      '^/api': 'http://f.apiplus.cn' //路径重写 
      } 
  } 
}

(2)请求接口时加上‘/api’前缀

getData () { 
 axios.get('/api/bj11x5.json', function (res) { 
   console.log(res) 
 })

 2.生产环境解决跨域问题流程如下

(1)打包

我们通过win+R命令打开CMD窗口,找到我们项目根目录 运行 npm run build命令

(2)服务器安装nginx服务器

  安装步骤 https://www.cnblogs.com/AlanLee/p/9044644.html

(3)配置nginx

  找到nginx的配置文件  nginx.conf ,它的路径是 /etc/nginx/nginx.conf

  nginx.conf的配置如下

server {
        listen       8000;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;
        location /api {
            proxy_pass https://www.baidu.com;  #代理的域名
            add_header 'Access-Control-Allow-Origin' '*'; 
            add_header 'Access-Control-Allow-Credentials' 'true'; 
        }
        location  / {
            root   /var/www/vue/;
            index  index.html index.htm;
        }
    }

解释如下:

  https://www.baidu.com 是我们要代理域名

  add_header 是增加返回头  解决跨域问题

注意:vue项目在请求域名的前面就要加上“/api”字符串,请求示例如下

test.post('/api/product/getData',params)
发布了42 篇原创文章 · 获赞 19 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/weixin_38639882/article/details/102530795
今日推荐