最近用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);