当咱们前端要调用跨域接口时,咱们须要用代理解决跨域问题,好比Vue的代理配置proxy,可是当Vue项目打包成静态文件时,他的代理也就失灵了,由于代理的前提是本地必须有service,本章讲一下生产环境的Vue项目如何作代理。javascript
本章咱们从两方面讲解Vue解决跨域的方案,一种是本地开发环境,另外一种是生产环境(nginx解决vue跨域问题)html
1.Vue本地(开发环境)解决跨域流程以下前端
(1)打开config/index.js,在proxyTable中添写以下代码:vue
proxyTable: { '/api': { //使用"/api"来代替"http://f.apiplus.c" target: 'http://f.apiplus.cn', //源地址 changeOrigin: true, //改变源 pathRewrite: { '^/api': 'http://f.apiplus.cn' //路径重写 } } }
(2)请求接口时加上‘/api’前缀java
getData () { axios.get('/api/bj11x5.json', function (res) { console.log(res) })
2.生产环境解决跨域问题流程以下python
(1)打包ios
咱们经过win+R命令打开CMD窗口,找到咱们项目根目录 运行 npm run build命令nginx
(2)服务器安装nginx服务器npm
安装步骤 http://www.javashuo.com/article/p-kgmiqnah-dw.htmljson
(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)