vue下axios和fetch跨域请求

1.在config的index.js下面进行常用跨域配置代码;
proxyTable: {
'/apis': { //使用"/api"来代替"http://xxxx.cn" target: 'http://xxxx.cn', //源地址 (接口域名) changeOrigin: true, //改变源 (是否跨域) pathRewrite: { '^/apis': 'http://xxxx.cn' //路径重写 (正常请求接口的简写) } } }
2.利用axios的post方式组件内发起请求
this
.$axios.post("/apis/test/testToken.php",{username:"hello",password:"123456"}) .then(res => { console.log(res) }).catch(err=>{ console.log(err) })
3.这几个axios常用设置可在封装axios的api中写上也可以在main.js写上
axios.defaults.headers.common['token'] = "f4c902c9ae5a2a9d8f84868ad064e706" //设置header里面的token依据需求设置 axios.defaults.headers.post["Content-type"] = "application/json" //设置请求头可要可不要 Vue.prototype.$http = axios //全局可要使用this.$http来发起请求
4.使用fetch API的形式请求接口数据
fetch("/apis/test/testToken.php", { method: "post", headers: { "Content-type": "application/json", token: "f4c902c9ae5a2a9d8f84868ad064e706" }, body: JSON.stringify({ username: "henry", password: "321321" }) }) .then(result => { console.log(result) return result.json() }) .then(data => { console.log(data) })

猜你喜欢

转载自www.cnblogs.com/lhl66/p/8856815.html