vue 使用代理解决跨域问题

简介

  • 使用代理,则前端不需要再配置baseURL,因为请求全部走的前端服务(代理)

开发环境

  • 在前端配置
// 在根目录创建vue.config.js文件
module.exports = {
    
    
  // 请求单个
  devServer: {
    
      
    proxy: '开发环境后台地址'
  },

  // 请求多个
  devServer: {
    
      
    proxy: {
    
    
      '自定义前端请求前缀': {
    
    
        target: '开发环境后台地址',
        pathRewrite: {
    
    
          '^/自定义前端请求前缀': '/后台真实前缀'
        }
      }
    }
  }
}
/*
示例: 远程服务器未处理跨域,接口为: http://localhost:3000/api/
本地开发环境中的url为: http://localhost:8080
1.  proxy: {
2.    '/api5': {
3.        target: 'http://localhost:3000',
4.        pathRewrite: {
5.            '^/api5' : '/api'
6.        }
7.     }
8.   } 
其中
第2行中的 '/api5'是自定义的本地请求时的名字
第3行的target表示代理的服务器url
第4行的pathRewrite表示路径重写
第5行的'^/api5'是一个正则表达式,表示要匹配请求的url中,全部'http://localhost:8080/api5' 转接为 http://localhost:3000/api
*/
  • 配置完之后,请求的接口地址就需要是当前前端服务的地址

    正常开发http://localhost:3000 -> 请求地址http://localhost:8080

    既然请求自己的地址,那么localhost:8080 直接写 / 即可 http://localhost:8080/api/xxx -> /api/xxx

    那么,请求地址为http://localhost:3000/api/xxx的可以写成/api/xxx即可请求成功

  • 此时,不需要配置axios的baseURL,也不需要添加任何的域名

生产环境

  • build之后,页面变成静态页面(proxy设置只能针对开发环境)

  • 生产环境需要配置nginx

server {
  listen       80;
  server_name  localhost;

  #charset koi8-r;

  #access_log  logs/host.access.log  main;

  location / {
    root   html;
    # 只能有一个
    # 没有使用history 
    index  index.html index.htm;
    # 使用了history
    try_files $uri $uri/ /index.html;

  }
  
  # 配置代理
  location /服务器前缀 {
    proxy_pass http://要代理的服务器地址(生产服务器地址);
  }

  # 配置代理 需要进行rewrite
  location /前端请求的前缀 {
    rewrite  ^/前端请求前缀/(.*)$ /后台接口真实前缀/$1 break;
    proxy_pass http://要代理的服务器地址(生产服务器地址);
  }
  

  error_page   500 502 503 504  /50x.html;
  location = /50x.html {
      root   html;
  }
}

猜你喜欢

转载自blog.csdn.net/weixin_49524462/article/details/116132443