vue调用api接口解决跨域问题

vue-cli3构建的项目:

  在vue.config.js的devServer中配置proxy    

devServer:{
    port:8086, // 启动端口
    open:false,  // 启动后是否自动打开网页
    proxy: {
      '/api': {
        target: 'http://s.gecimi.com', //要跨域的域名
        secure:true ,//接受对方是https的接口
        ws: true, // 是否启用websockets
        changeOrigin: true, //是否允许跨越
        pathRewrite: {
          '^/api': '/'  //将你的地址代理位这个 /api 接下来请求时就使用这个/api来代替你的地址
        },
      }
    }

1、target是要代理的域名

2、使用'/api'代替target里面的地址,组件中调用接口时直接用'/api'代替,例如调用'http://xxx.com/lrc',直接写'/api/lrc‘即可

webpack构建的项目,

proxy: {
      '/api': {
        target: 'http://s.gecimi.com', //要跨域的域名
        secure:true ,//接受对方是https的接口
        ws: true, // 是否启用websockets
        changeOrigin: true, //是否允许跨越
        pathRewrite: {
          '^/api': '/'  //将你的地址代理位这个 /api 接下来请求时就使用这个/api来代替你的地址
        },
      }

 

posted @ 2021-03-31 21:25  xing柠檬  阅读(2630)  评论(0编辑  收藏  举报