axios请求接口http_使用axios请求接口,几种content-type的区别详解
axios的使用
安裝(一般使用框架的話, 腳手架都集成了)
$ npm install axios
請求示例
// POST
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// GET
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// 執行多個并發
axios.all([get1(), get2()])
.then(axios.spread(function (acct, perms) {
// 兩個請求現在都執行完成
}));
可以通過向 axios 傳遞相關配置來創建請求
語法: axios(config)
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
這里, 我就拿以POST的方式傳遞相關配置來說事, 因為筆者在這里躺了兩次坑, 很有必要記錄一下, 哈哈.
默認情況下, 不寫content-type, 是以json的方式來傳遞, (Content-Type: application/json;charset=UTF-8)
axios({
url:'/api/connect/token',
method: 'post',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
}).then(res => {
console.log(1234, res.data)
}).catch(error => {
console.log(error)
})
Headers如下:
Request Payload
{ firstName: "Fred", lastName: "Flintstone"}
content-type改成x-www-form-urlencoded, 即表單提交方式
axios({
url:'/api/connect/token',
method: 'post',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
},
headers: {
'Content-type': 'application/x-www-form-urlencoded'
}
}).then(res => {
console.log(1234, res.data)
}).catch(error => {
console.log(error)
})
Headers如下:
Form Data
{"firstName":"Fred","lastName":"Flintstone"}:
另一種情況, 序列化成字符串形式傳遞
axios({
url:'/api/connect/token',
method: 'post',
data: JSON.stringify({
firstName: 'Fred',
lastName: 'Flintstone'
})
}).then(res => {
console.log(1234, res.data)
}).catch(error => {
console.log(error)
})
結果跟上面一致:
Form Data
{"firstName":"Fred","lastName":"Flintstone"}:
還有一種常見情況, 通過qs庫對數據進行編碼(前提要安裝qs)
import qs from 'qs'
axios({
url:'/api/connect/token',
method: 'post',
data: qs.stringify({
firstName: 'Fred',
lastName: 'Flintstone'
})
}).then(res => {
console.log(1234, res.data)
}).catch(error => {
console.log(error)
})
結果:
Request Headers
Content-Type: application/x-www-form-urlencoded
Form Data
firstName: Fred
lastName: Flintstone
使用qs要注意的點 :
allowDots(多層對象嵌套, 可用.標記)
qs.stringify({
a: {
b: {
c: 'd', e: 'f'
}
}
}, { allowDots: true });
// 'a.b.c=d&a.b.e=f'
以上這篇使用axios請求接口,幾種content-type的區別詳解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持我們。
本文標題: 使用axios請求接口,幾種content-type的區別詳解
本文地址: http://www.cppcns.com/wangluo/javascript/283227.html
總結
以上是生活随笔為你收集整理的axios请求接口http_使用axios请求接口,几种content-type的区别详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 钢铁侠机器人公仔_这个618,买个钢铁侠
- 下一篇: 单片机机器周期怎么计算公式_单片机很好玩