vue2.x实现跨域(proxytable)请求fetch/axios

通过vue-cli2.x创建的项目实现跨域
1.找到config文件夹
2.在inde.js文件中找到proxytable{}
3.添加代码
proxyTable: {
      '/api': {
        target: 'http://xxxxxx.com', // 请求的接口的域名
        // secure: false,  // 如果是https接口,需要配置这个参数
        changeOrigin: true, // 如果接口跨域,需要进行这个参数配置
        pathRewrite: {
          '^/api': ''
        }
      }
    },
    //当你发起请求时前面加上'/api/'就代表着'http://xxxxxx.com'
    // 注意: '/api' 为匹配项,target 为被请求的地址,因为在 ajax 的 url 中加了前缀 '/api',而原本的接口是没有这个前缀的,所以需要通过 pathRewrite 来重写地址,将前缀 '/api' 转为 '/'。如果本身的接口地址就有 '/api' 这种通用前缀,就可以把 pathRewrite 删掉。
通过fetch请求
 1 export defalut{
 2     created(){
 3         fetch('地址',{
 4             method:'post',//请求的方式
 5             //请求头
 6             headers:{
 7                 'Content-type':'application/json',
 8                 token:'',
 9             },
10             // body:'post请求的参数',
11             body:JSON.stringify({username:,password:})
12         })
13         .then(result=>{//请求成功的结果
14             console.log(result)
15         })
16     }
17 }
通过axios请求
先下载axios,npm install axios
在main.js中引入配置
1 import axios form 'axios'
2 //设置请求的headers
3 axios.defaults.headers.common['token']=''
4 axios.defaults.headers.post['Content-type']='application/json'
5 Vue.prototype.$axios=axios
在组件中使用axios
 1 export defalut{
 2     created(){
 3         this.$axios.post('地址',{
 4             //参数
 5         })
 6         .then(data=>{
 7             console.log(data)
 8         })
 9     }
10 }

猜你喜欢

转载自www.cnblogs.com/chenfan19941111/p/9747574.html