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

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

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

(1)打开vue.config.js,在module.exports中添写如下代码:

devServer: {
    port: port,
    open: true,
    overlay: {
      warnings: false,
      errors: true
    },
    proxy: {
      '/api': {
        target: process.env.VUE_APP_BASE_API,
        changeOrigin: true,
        pathRewrite: {
          '^/api': 'api'
        }
      }
    }
  },

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

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

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

(1)打包

我们通过terminal窗口,找到我们项目根目录 运行 npm run build命令
(2)服务器安装nginx服务器
(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)

实战

nginx部署vue-admin-template
打包部署vue-admin-template项目
npm run build:stage
配置nginx配置文件

进入nginx文件夹下的conf文件,打开nginx.conf文件,修改端口以及配置子目录

server {
    listen       8000;
    server_name  localhost;

    #charset koi8-r;

    #access_log  logs/host.access.log  main;
    location  /doctor {
        root   /var/www/vue/;
        index  index.html index.htm;
    }
}

3、部署
在nginx目录里面的html文件夹中新建doctor文件夹
将vue-admin-template项目中的dist文件夹下的所有东西复制粘贴到nginx目录下的html下的doctor文件夹中。
重启nginx,在浏览器输入localhost:8090/doctor,进入网站页面

错误处理

虽然项目部署启动成功,但是当点击登录时报请求失败,使用火狐浏览器打开控制台的network,可以看到该请求路径的前面加了一个前缀/stage-api,使原后端接口请求由/doctor/login变为/stage-api/doctor/login。

使用nginx代理可以解决此问题:打开nginx.conf文件配置以下内容

location /stage-api {
    proxy_pass https://www.baidu.com;  #代理的域名
    add_header 'Access-Control-Allow-Origin' '*'; 
    add_header 'Access-Control-Allow-Credentials' 'true'; 
}
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐