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);
});
And this is the code for the backend:
authRouter.post('/register', (request, response) => {
console.log(request.body);
});
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);
The issue came from the fact that body-parser
wants an x-www-form-urlencoded
request, and I wasn't providing one.
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);
});
in my case I declare "Content-Type": "application / json" in the axios headers. For ease, I declare in the global attribute of axios.
in this way
axios.defaults.headers.common = {
"Content-Type": "application/json"
}
Now its works
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With