Node.js找不到 Axios 主体请求参数



我有一个 Node.js API,它接受一个名称并给出 422 验证错误。

// Express is setup with bodyParser:
const bodyParser = require('body-parser');
const app = express()
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
app.use(express.static('files'))
...
// API:
app.post('/test',
[
body('name').exists(),
],
async (req, res, next) => {
try{ 
const errors = validationResult(req);
if(!errors.isEmpty()){
return res.status(422).json({ errors: errors.array() });
}
return res.status(200).send('Your name is ' + req.body.name);
}catch(error){
return res.status(422).json({ errors: errors.array() });
}
}

我使用 Axios 访问它:

const rb = {
name : 'John', 
} 
const config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
params: {
name : 'John'
}
}
axios.post(url, rb, config)
.then((result) => {
callback('Success', result);
})
.catch((err) => {
callback('Oops!', err);
});

我正在返回第一个 422,我的"name"参数没有被 Node.js 解析。 它不在 req.body 中

我是否通过 Axios 发送了错误的请求? 它在邮递员中工作。

rb应该是作为请求正文传递的对象:

axios.post(url, { name : 'John' }, config)

params配置选项用于传递查询/URL 参数(可通过req.query访问(。

鉴于它在邮递员中工作,我假设您的 Express 服务器正在使用正确的正文解析器 (express.urlencoded(。

最新更新