req.body returning Undefined when using consign in the application

Asked

Viewed 407 times

1

I am familiar with express, so I created a simple form with two fields, I have a JS file where I receive the data of the form and send them through the xmlHttpRequest and on the server side, I’m using consign to manage my routes, the problem, is that whenever I add it, the return of the method that receives the form post on the server side always returns Undefined.

form

<form id="form">
  <input type="text" name="name" id="name" id='form'>
  <input type="password" name="password" id="password">
  <button type="submit">Salvar</button>
</form>

app.js (Where I capture the form)

document.querySelector('#form').addEventListener('submit', (event) => {
  event.preventDefault();

  const name = document.querySelector('#name');
  const password = document.querySelector('#password');

  const person = {
    name: name.value,
    password: password.value,
  };

  console.log(person); //imprime o que eu quero normalmente

  const xhr = new XMLHttpRequest();
  xhr.open('POST', '/person', true);
  xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
  xhr.send(JSON.stringify(person));
});

index.js (where I set up express)

let express = require('express');
let bodyParser = require('body-parser');
let consign = require('consign');

let app = express();

app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

app.use(express.static('public'));

consign().include('routes').into(app);

app.listen(3000, () => {
  console.log('rodando');
});

On that floor above, if I take the let consign, the line where I give a include on it and add an app.post to the route /users I can receive the data normally.

This is the file that is inside Routes and that is returning Undefined:

module.exports = (app) => {
  const person = app.route('/person');

  person.post((req, res) => {
    console.log(req.body.value);
  });
}
  • No need for this value in req.body.value

  • You will only have access to key’s name and password (req.body.name, req.body.password)

  • @Cláudiohilário my req.body was Undefined. I stopped using the consign and started using the express.Router() same, I think it was some conflict then....

  • @Valdeirpsr my req.body was Undefined. I stopped using the consign and started using the express.Router() even, I think it was some conflict then...

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.