Axios posting empty request
Axios posting empty request
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
body
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:
request.body
JSON
authRouter
module.export
app
app
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
Do you have JSON parsing middleware?
– Jordan S
Jul 2 at 21:10
Yes, I edited my question to include
app configuration.– Justplayit
Jul 2 at 21:18
app
I'm guessing that the
body-parser might be the issue, since on another occasion, I was using this module without urlencoded part, and I had no problem.– Justplayit
Jul 2 at 21:19
body-parser
urlencoded
Or an
axios header problem. I see that I should use Content-Type application/x-www-form-urlencoded, but isn't this axios default?– Justplayit
Jul 2 at 21:22
axios
Content-Type application/x-www-form-urlencoded
axios
1 Answer
1
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:
body-parser
x-www-form-urlencoded
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);
});
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Are you using
body-parserproperly?– Patrick Roberts
Jul 2 at 21:10