Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Axios posting empty request

Tags:

node.js

axios

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);
like image 988
Justplayit Avatar asked Jul 02 '18 21:07

Justplayit


2 Answers

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);
  });
like image 99
Justplayit Avatar answered Oct 17 '22 05:10

Justplayit


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

like image 30
Rafael Menicucci Avatar answered Oct 17 '22 04:10

Rafael Menicucci