vue?cli3?項目中如何使用axios發(fā)送post請求
使用axios發(fā)送post請求
react 同樣適用
首先需要安裝對應的第三方包
- cnpm i -S axios
- cnpm i -S lodash
然后在做下邊的
在vue 項目中創(chuàng)建一個這樣的文件目錄

發(fā)送post請求
index.js中的文件內容是:
import axios from "axios"
import _ from "lodash"
// 處理請求參數
const coverFormData = (obj) => {
let data = Object.keys(obj.data).map(item => {
let value = obj.data[item];
if(_.isArray(value) || _.isObject(value)){
value = JSON.stringify(value)
}
return encodeURIComponent(item) + '=' + encodeURIComponent(value);
}).join('&');
return {data: data, url: obj.url};
}
function post(obj) {
const { data, url } = coverFormData(obj);
return new Promise((resolve, reject) => {
axios.post(url, data)
.then(res => {
// obj.success ? obj.success(res) : null
resolve(res.data);
})
.catch(error => {
// obj.error ? obj.error(error) : null;
reject(error);
})
})
}
let requests = {}
requests.post = post
export default requests使用:

效果:

發(fā)送get請求將index.js中再添加如下代碼
requests.get = obj => {
const { data, url } = coverFormData(obj);
return new Promise((resolve, reject) => {
axios.get(url + '?' + data).then(res => {
obj.success ? obj.success(res) : null;
resolve(res.data);
}).catch(error => {
obj.error ? obj.error(error) : null;
reject(error);
})
})
}使用和post的一模一樣只是將requests.post改成request.get
vue使用axios的踩坑記錄
axios跨域
在自己寫的一個項目中,想要直接將學號和密碼發(fā)到學校的教務系統(tǒng),結果跨域了。。。。。。
原代碼
// url為要訪問的域名
axios.get(`${url}?method=authUser&xh=${this.sNo}&pwd=${this.password}`)
.then((res) => {
// ...
}).catch((err) => {
// ...
})

在網上找解決跨域的問題時,看到很多都是修改config下的…文件,但是vue-cli腳手架創(chuàng)建的vue3項目中并沒有config文件夾,所以直接去到官方文檔查找配置
解決方法
在package.json同級文件夾下創(chuàng)建vue.config.js,配置如下
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'url', //設置要訪問的域名和端口號
changeOrigin: true, //設置為跨域
pathRewrite: {
'^/api': '/' //這里理解成用‘/api'代替target里面的地址,在后面發(fā)起請求時,/api就會代替target中的值,可以實現跨域
}
}
}
}
}
修改我們的請求代碼
axios.get(`/api/app.do?method=authUser&xh=${this.sNo}&pwd=${this.password}`)
.then((res) => {
// ...
}).catch((err) => {
// ...
})
這里使用/api替換了原來的url,實現跨域
axios發(fā)起post請求后端無法接收數據
在第一次使用axios向后臺發(fā)送post請求時,發(fā)現自己發(fā)送的數據后端沒有接收到,后端用的是spring框架,但是同樣的請求我使用自己的node服務器測試時卻好好的
原代碼
axios.post(url,{data:data})
.then(res => {
// ...
}).catch(err => {
// ...
})
我用node服務器打印請求發(fā)過拉的數據,都能得到{"data":1},但是后端那里總是只能得到null
在查看前后端代碼后總是覺得沒問題,唯一的變數只有axios了,所以去到淘寶鏡像上看axios的使用,看到特性里面的概述

大概就是說可以對請求中的數據和響應的數據做格式轉換,而且會自動對json數據做轉換,我嘗試將上面的請求改成使用非json格式傳輸
axios.post(url,`data=${data}`)
.then(res => {
// ...
}).catch(err => {
// ...
})
意料之中的成功了,那么為什么呢,在查閱資料后,終于在GitHub上找到了對應的源碼
transformRequest: [function transformRequest(data, headers) {
normalizeHeaderName(headers, 'Accept');
normalizeHeaderName(headers, 'Content-Type');
if (utils.isFormData(data) ||
utils.isArrayBuffer(data) ||
utils.isBuffer(data) ||
utils.isStream(data) ||
utils.isFile(data) ||
utils.isBlob(data)
) {
return data;
}
if (utils.isArrayBufferView(data)) {
return data.buffer;
}
if (utils.isURLSearchParams(data)) {
setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');
return data.toString();
}
// 看這里------------------------------------------
if (utils.isObject(data)) {
setContentTypeIfUnset(headers, 'application/json;charset=utf-8');
return JSON.stringify(data);
}
return data;
}]
當判斷為對象時,會把headers設置為application/json;charset=utf-8,也就是Content-Type,而根據項目組里的后端同學所說的,服務端要求的是Content-Type': 'application/x-www-form-urlencoded,我試著在發(fā)送請求前將headers設置為application/x-www-form-urlencoded,結果還是不行,大概是因為源碼中對headers的修改在自己的設置之后實現的,但是這樣寫的話,要寫出一串很長的字符串,感覺挺麻煩的,那就可以嘗試下面的方法
因為源碼中是通過transformRequest來修改headers的,而這個方法我們其實也可以自己實現,所以我們只要在發(fā)送請求的時候自己來實現這個方法就可以了,這里通過修改data的數據結構來達到目的
import Qs from 'qs'
axios({
url:url,
data:{
data:data
},
transformRequest: [function (data) {
// 對data的數據格式進行修改
return Qs.stringify(data)
}],
headers: {
'deviceCode': 'A95ZEF1-47B5-AC90BF3'
})
.then(res => {
// ...
}).catch(err => {
// ...
})
上面是將data的數據格式進行轉換,但是我們也可以選擇修改處理data的方式
axios({
url:url,
data:{
data:data
},
transformRequest: [function transformRequest(data, headers) {
normalizeHeaderName(headers, 'Accept');
normalizeHeaderName(headers, 'Content-Type');
if (utils.isFormData(data) ||
utils.isArrayBuffer(data) ||
utils.isBuffer(data) ||
utils.isStream(data) ||
utils.isFile(data) ||
utils.isBlob(data)
) {
return data;
}
if (utils.isArrayBufferView(data)) {
return data.buffer;
}
if (utils.isURLSearchParams(data)) {
setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');
return data.toString();
}
// 看這里------------------------------------------
if (utils.isObject(data)) {
setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');
let _data = Object.keys(data)
return encodeURI(_data.map(name => `${name}=${data[name]}`).join('&'));
}
return data;
}])
.then(res => {
// ...
}).catch(err => {
// ...
})
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
詳解如何在Vue3+TS的項目中使用NProgress進度條
本文主要介紹了詳解如何在Vue3+TS的項目中使用NProgress進度條,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-06-06

