axios用post傳參,後端無法獲取參數問題

最近用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);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章