Axios请求正文在快递服务器中被奇怪地解析

时间:2019-03-20 14:07:13

标签: node.js express axios

我有nodejs个快递服务器和nodejs axios个客户端,我尝试使用x-www-form-urlencoded标头发送帖子数据。

app.post('/login', (req, res) => { 
   const { username, password } = req.body
   console.log(req.body) 
 })

nodejs axios客户端的请求正文:

{ '{"username":"gefalko","password":"mypass"}': '' }

邮递员客户的请求正文:

{"username":"gefalko","password":"mypass"}

我使用'body-parser'https://www.npmjs.com/package/body-parser中间件在服务器上进行请求正文解析。

app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json()) 

和我的axios代码如下:

const axios = require('axios')
const prompt = require('prompt')

var prompt_attributes = [
    {
        name: 'username',
        validator: /^[a-zA-Z\s\-]+$/,
        warning: 'Username is not valid, it can only contains letters, spaces, or dashes'
    },
    {
        name: 'password',
        hidden: true
    }
]

prompt.start();

prompt.get(prompt_attributes, function (err, result) {
    if (err) {
        console.log(err);
        return 1;
    }else {
        console.log('Command-line received data:');
        const username = result.username
        const password = result.password

        const config = {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        }

        const reqBody =  {
          username: username,
          password: password
        }

        axios.post('http://localhost:3005/login', reqBody, config).then(response => {
          console.log(response.data);
        }).catch(error => {
          console.log(error);
        })
    }
});

0 个答案:

没有答案