title: Vue ProxyTable 跨域 部署Nginxdate: 2020-07-01 16:01:33
categories: Config
tags: config

说明:proxyTable 只是前端开发调试时有效,真正的转发需要Nginx。

整体流程:
前端地址:10.10.3.120:8080 后端地址:10.10.3.120:8082
vue请求 10.10.3.120:8080/api/login —> nginx得到/api/login—>nginx转发到10.10.3.120:8082/api/login
也就是说,这个过程和proxyTable 的转发没关系了。

Vue前端配置

1 vue proxtTable 配置

  1. dev: {
  2. port: 80,
  3. assetsSubDirectory: 'static', //打包后生成的路径名
  4. assetsPublicPath: '/',
  5. proxyTable: {
  6. '/api': {
  7. target: 'http://10.10.3.120:8082', //服务器ip地址
  8. changeOrigin: true, // 是否跨域
  9. pathRewrite: { //pathRewrite可以不加
  10. '^/api': '/api' // 这种接口配置出来 http://10.10.3.120:8082/api/login
  11. '^/api': '/' // 这种接口配置出来 http://10.10.3.120:8082/login
  12. }
  13. }
  14. }
  15. }

请求使用

  1. // 登录
  2. login(){
  3. this.$ajaxget({
  4. url: '/api/login',
  5. data: {},
  6. successFc: data => {
  7. console.log(data.data)
  8. }
  9. })
  10. },

2 打包上传,不需要特殊修改代码

打包好的代码位于dist目录下,上传dist文件夹到服务器指定路径
Vue ProxyTable 跨域 部署Nginx - 图1

Nginx 配置

1 配置nginx.conf

  1. http {
  2. //xxx
  3. //xxx
  4. #前端代理
  5. server {
  6. listen 8080;
  7. server_name localhost;
  8. location /{
  9. root /var/www/dist/; #前端代码存放地址
  10. index index.html index.htm;
  11. }
  12. #前端proxyTable(重点)
  13. location /api/ { #此名称api对应vue的proxyTable名称
  14. proxy_pass http://10.10.3.120:8082/; #对应proxyTable的target地址
  15. }
  16. }
  17. }

ngnx转发超时(org.apache.catalina.connector.ClientabortException:java.io.IOException:Broken pipe)

  1. #代理转发超时配置(broken pipe错误)
  2. proxy_send_timeout 1200s;
  3. proxy_read_timeout 1200s;
  4. proxy_connect_timeout 1200s;
  5. send_timeout 1200s;

2 启动nginx

  1. service nginx start

3 访问

  1. http://10.10.3.120:8080

转发地址

  1. 假设下面四种情况分别用 http://192.168.1.1/proxy/test.html 进行访问。
  2. 第一种:
  3. location /proxy/ {
  4. proxy_pass http://127.0.0.1/;
  5. }
  6. 代理到URL:http://127.0.0.1/test.html
  7. 第二种(相对于第一种,最后少一个 / )
  8. location /proxy/ {
  9. proxy_pass http://127.0.0.1;
  10. }
  11. 代理到URL:http://127.0.0.1/proxy/test.html
  12. 第三种:
  13. location /proxy/ {
  14. proxy_pass http://127.0.0.1/aaa/;
  15. }
  16. 代理到URL:http://127.0.0.1/aaa/test.html
  17. 第四种(相对于第三种,最后少一个 / )
  18. location /proxy/ {
  19. proxy_pass http://127.0.0.1/aaa;
  20. }
  21. 代理到URL:http://127.0.0.1/aaatest.html