vue不同环境使用axios跨域,前端解决方案

116 阅读1分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第25天,点击查看活动详情

  1. development 环境 只需要在config->index.js dev模块中添加proxyTable 即可 在这里插入图片描述

    proxyTable: {
    		//当请求中以/api 开头时,对将/api请求路径进行代理
          '/api': {
            //接口域名
            target: 'http://localhost:3000/',
            // 如果接口跨域,需要进行这个参数配置,为true的话,请求的header将会设置为匹配目标服务器的规则(Access-Control-Allow-Origin)而跨域设置后端是在response中设置
            changeOrigin: true,
            //重写/api  为 /
            pathRewrite: {
              '^/api': '/'
            }
          }
        },
        全部意义: 当发送localhost:8080/api/test 时,将请求代理到http://localhost:3000/test   因为重写了/api 为 /。
        如果不重写,去掉pathReWrite配置。当发送localhost:8080/api/test 时,将请求代理到http://localhost:3000/api/test
    

    其实请求接口 也可以不用写 /api 来请求,可以直接配置‘/’ 因为后端真实接口为 ‘/’ 开头

    proxyTable: {
      '/': {
        target: 'http://localhost:3000/', 
        changeOrigin: true,
      }
    },
    全部意义: 当发送localhost:8080/test 时,将请求代理到http://localhost:3000/test 
    

    真实axios 请求情况

    goInfo(item){
      let playListUrl = `/playlist/detail?id=${item.id}`;
      axios.get(playListUrl).then((response) => {
        xxxxx
    },
    

    问题:那为什么要写 /api 呢?因为生产环境和开发 不一样,开发环境一般都是采用nginx+tomcat / 或者单纯用nginx。利用nginx 做代理,可以解决跨域问题。而location / 模块映射 和 location /api 模块 映射应该要区分开来。一个专门做静态文件访问,一个专门做请求代理

  2. product 环境

    #xi-music项目  注意当前域名
    server {
       // xxxxx 这部分省略
    
        location / {
        	#当请求路径以根路径开头时,去/usr/lcoal下找静态资源,默认index.html
        	#示例:/xi    映射为   /usr/local/xi 
            root   /usr/local;
            index  index.html index.htm;
           # 尝试读取文件 $uri代表  当前请求子路径, $uri/  代表请求的目录
           #如果前两项都没有匹配,那么重新发送请求/xi-music
           #解决刷新404问题
            try_files  $uri $uri/ /xi-music;
        }
    
    	 #添加访问目录为/api的代理配置,使以“/api”开头的地址都转到“http://127.0.0.1:3000”上
    	location /api {
    		rewrite  ^/api/(.*)$ /$1 break;
    		# 将/api下的子路径  拼接到http://localhost:3000下
    		# /api/song     http://localhost:3000/song
    		proxy_pass   http://127.0.0.1:3000;
        }
        
    }