vue项目开发环境的跨域问题

一、使用脚手架自带的代理机制

config下的index.js中的proxyTable的配置

dev: {  
  // Paths  
  assetsSubDirectory: 'static',  
  assetsPublicPath: './',  
  proxyTable: {
   '/api': {
     target: 'http://news.baidu.com', 
    secure: true, 
    changeOrigin: true,  
    pathRewrite: {
     '^/api': '/api'  
    }
   }
  }, 

1、这里理解成用'/api'代替target里面的地址,后面组件中我们掉接口时直接用api代替 比如我用'http://40.00.100.100:3002/user/add',直接写'/api/user/add'即可 

2、target : 你要跨域的网址 比如 'http://news.baidu.com'

3、secure: /如果是https接口,需要配置这个参数

4、changeOrigin:这个参数是用来回避跨站问题的,配置完之后发请求时会自动修改http header  里面的host,但是不会修改别的 。

5、pathRewrite:路径的替换规则这里的配置是正则表达式,以/api开头的将会被用用‘/api'替换掉,假如后台文档 的接口是 /api/list/xxx前端api接口写:axios.get('/api/list/xxx') , 被处理之后实际访问的是:  http://news.baidu.com/api/list/xxx 

二、在axios中使用

axios({  
        method: 'get',  
        baseURL: '/api',  
        url: 'product/list.do?keyword=手机'  
      }).then(  
        res => {  
          console.log(res.data.data.list[0].name);  
        }  
      ).catch(  
        err => {  
          console.log(err);  
        }  
      ); 

猜你喜欢

转载自blog.csdn.net/weixin_43182021/article/details/84334371