我有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);
})
}
});