vue 跨域请求(fetch/axios/proxytable)

#### 跨域接口地址: http://www/thenewstep.cn/test/testToken.php
#### 参数: username,password
#### token: f4c902c9ae5a2a9d8f84868ad064e706
#### 请求类型: post
#### 请求头:  Content-type:application/json

在app.vue中写个钩子函数

created() {

    // fetch

     fetch("http://www/thenewstep.cn/test/testToken.php",{

         method:"post",

         body:"hello"

    })

    .then(result => {

         console.log(result)

     })

}

以上代码会报跨域的问题

解决方案

在config下的index.js中的proxyTable中赋值

proxyTable:{

    '/apis':{

         target:'http://www/thenewstep.cn',// 接口域名

         changeOrigin: true, // 是否跨域

         pathRewrite: {

             '^/apis': ' '  // 需要rewrite重写的

         }

    }

}

替换钩子函数中的路径,然后重启

created() {

    // fetch

     fetch("/aips/test/testToken.php",{

         method:"post",

         headers:{

            "Content-type":"application/json",

            token:"f4c902c9ae5a2a9d8f84868ad064e706"

         },

         body:JSON.stringify({username:"henry",password:"123456"})

    })

    .then(result => {

       return result.json()

     })

     .then(data => {

         console.log(data)

     })

}

 

 

使用axios

1.安装axios模块

npm install axios

2.重启

npm run dev

3.在main.js中引入axios

import axios from 'axios'

4.为了全局使用添加到vue的原型上

Vue.prototype.$axios = axios

5.在App.vue中使用

// axios

this.$axios.post("/apis/test/testToken.php",{username:"hello",password:"123"})

     .then(data => {

          console.log(data)

      })

6.在main.js中设置token,post请求头等

axios.defaults.headers.common['token'] = "f4c902c9ae5a2a9d8f84868ad064e706"

axios.defaults.headers.post["Content-type"] ="application/json"

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值