问题描述
我正在尝试向后端发送一个 axios
请求,但它最终有一个空的 body
,我不明白它为什么这样做.这是请求的代码:
I am trying to send an axios
request to the backend, but it ends up having an empty body
, and i do not understand why it does that.This is the code for the request:
axios.post('/register', {email: email, password: password, username: username, company: company}).then(response => {
console.log(response.data);
});
这是后端的代码:
authRouter.post('/register', (request, response) => {
console.log(request.body);
});
这个输出一个空的request.body
.我还检查了发送的 JSON
,它根本不是空的.有没有办法在发送之前查看请求的形式?这个 authRouter
是一个 module.export
,它被主要的 app
模块使用.这个 app
模块有这样的配置:
And this one outputs an empty request.body
. I've also checked the JSON
sent, and it is not empty at all. Is there a way to see what is the form of the request before being sent?This authRouter
is a module.export
, that is being used by the main app
module. This app
module has this configuration:
app.use(express.static("public"));
app.use(session({ secret: "shh", resave: false, saveUninitialized: false }));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(passport.initialize());
app.use(passport.session());
app.set('views', __dirname + '/views');
app.set('view engine', 'pug');
app.use(authRouter);
https.createServer({key: fs.readFileSync('ssl/key.pem'), cert: fs.readFileSync('ssl/cert.pem')}, app).listen(8080);
推荐答案
问题来自于 body-parser
想要一个 x-www-form-urlencoded
请求,我没有提供.
The issue came from the fact that body-parser
wants an x-www-form-urlencoded
request, and I wasn't providing one.
我已经为它设置了 axios 请求的头部,代码如下所示:
I've set the header for the axios request to it, and the code looks like this:
axios.post('/register', {
email: email,
password: password,
username: username,
company: company
}, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(response => {
console.log(response.data);
});
这篇关于Axios 发布空请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!