#### 跨域接口地址: 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"