axios用post傳參,後端無法獲取引數問題
阿新 • • 發佈:2020-02-02
最近用vue+nodejs寫專案,前端使用axios向後臺傳參,發現後臺接收不到引數。
後臺是node+express框架,然後使用了body-parser包接收引數,配置如下:
const express = require('express') const bodyParser = require('body-parser') const app = express() app.listen(8888, () => { console.log('Server start on 8888...') }) app.use(bodyParser.urlencoded({extended: true})
axios傳參,官方給了兩種方式。
方式一
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
方式二
axios({ method: 'post', url: '/user/12345', data: { firstName: 'Fred', lastName: 'Flintstone' } });
以上兩種方案我都試過,後臺都無法獲取到引數。
網上有不少解決方案說axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
或者 {headers:{'Content-Type':'application/x-www-form-urlencoded'}}
我也都試過,還是不行。
直到我看了一下axios的原始碼,想起了axios自動轉換json資料的特性:
所以以上兩種傳參方式,和後臺app.use(bodyParser.urlencoded({extended: true})的配置不適用,解決方式如下兩種:
解決方案一
前端傳參方式不變,後臺修改bodyParser的接收引數方式:
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
app.listen(8888, () => {
console.log('Server start on 8888...')
})
app.use(bodyParser.json())
解決方案二
後臺不用變,前端改變傳參方式如下:
const params = new URLSearchParams();
params.append('firstName', 'Fred');
params.append('lastName', 'Flintstone');
axios.post('/user/12345', params);