vue-cli4.0 和 nginx 反向代理跨域
文中本机测试地址
前端:http://localhost:8080/
后端:http://www.api.test
1. 前端代理配置:/config/index.js
1 proxyTable: { 2 // 以 /api 开头的请求 URL 3 '/api':{ 4 // 代理到的地址 5 target:'http://www.api.test', 6 // 请求的header将会设置为匹配目标服务器的规则 7 changeOrigin:true, 8 // 重写路径 9 pathRewrite:{ 10 '^/api':'/test' 11 } 12 } 13 }
2. 前端代码,如果上面代理以 /api 开头,那么axios的请求 URL 就要以 /api 开头
1 methods: { 2 // 发送 get 请求 3 sendGetFn () { 4 Axios.get('/api/01/index.php').then(res => { 5 this.msg = res.data 6 // 失败的回调函数 7 }).catch(error => { 8 this.error = error 9 }) 10 } 11 }
3. nginx配置
# vue-cli打包到线上后,需要配合nginx的反向代理才能访问到 api ,这个反向代理要设置在vue打包后上传的到 web 服务器上,不要在 api 接口服务器上设置,重要的事情说3遍,web服务器!web服务器!web服务器!
1 location ^~ /api { 2 rewrite ^/api/(.*)$ /test/$1 break; 3 proxy_pass http://www.api.test/; 4 }
由于我对 nginx也不懂,只能简单解释下上面参数的大概意思,
-
location- 如果求 URL 为:http://www.nginx.test/api/01/index.php ,那么 location 为:/api/01/index.php
-
^~ /api- 匹配任何以 /api 开头的请求
-
rewrite ^/api/(.*)$ /test/$1 break; - 几个参数的意思
- ^/api/(.*)$
- 正则表达式,匹配接口请求过来的 URL
- /test/$1
- 要替换成的重写后的 URL,$1为正则表达式里的子模式,也就是 (.*) 所匹配到内容 01/index.php,完整的替换结果是:/test/01.index.php
- 要替换成的重写后的 URL,$1为正则表达式里的子模式,也就是 (.*) 所匹配到内容 01/index.php,完整的替换结果是:/test/01.index.php
- break
- 标识位,停止检测
- ^/api/(.*)$
上面的配置可能一次不成功,就需要自己去调试了,找到 nginx 的安装目录下 /logs/logs/access.log 文件看发送的请求路径哪里拼错了
完整代码可以参考下面地址,前端页面是 /src/pages/Nginx.vue
https://git.lug.ustc.edu.cn/gechenpeng/axiostest.git

浙公网安备 33010602011771号