Vue项目中解决axios请求跨域问题(第三方接口)

先引入axios

在命令行输入 npm i axios 

然后再引入 import axios from 'axios' 这里不再赘述

首先明确自己的api接口,比如我的是  

http://testapi.tvm.com.cn/some/getsome

先去config/index.js中找到proxyTable

//如果你用vue-cli初始化一个项目,一般proxyTable中是空的

proxyTable:{}

//在里面填入:

proxyTable:{
    '/api': {
          target: 'http://testapi.tvm.com.cn',//设置你调用的接口域名和端口号 别忘了加http
          changeOrigin: true,
          pathRewrite: {
            '^/api': '',
           //这里理解成用'/api'代替target里面的地址,后面组件中我们掉接口时直接用api代替 比如我要调用'http://xxx.xxx.xxx.xx:8081/user/add',直接写‘/api/user/add’即可
          }
        }
}

上面pathRewrite中的注释不清楚,我再写一遍:

'/api'来代替target中的地址,以后再调用接口,比如http://testapi.tvm.com.cn/some/getsome

那么就直接写 '/api/some/getsome'

设置好之后,我们到一个组件中使用,上面已经引入了axios

let url='/api/some/getsome'
axios.get(url)
    .then(res=>{
        console.log(res)
    })
    .catch(err=>{
        console.log(err)
    })

这里多嘴一下,请求方式很多,有get/post/delete/put等等,需要添加参数,可以这么写

扫描二维码关注公众号,回复: 3659651 查看本文章
let url=''
let element='某些请求参数'
axios.get(url,element)
    .then
    .catch

~~~完事~~~

猜你喜欢

转载自blog.csdn.net/weixin_42580432/article/details/83107474