Get data stops with Node.JS

Asked

Viewed 78 times

0

I’m trying to get information sent via POST in Node.JS, thus: I call the API that:

$.ajax({
 method: 'POST',
 url: '/api/post',
 data: {
  xml: '<?xml version="1.0"?><query><author>John Steinbeck</author></query>'
 }
})

No Node configured this way:

const express = require('express');
const router = express.Router();
const path = require('path');

router.post('/api/post', (req, res) => {
  console.log(req.body);
  res.status(200).send('ok');
})

But this console.log(req.body) returns undefined.

  • if you only use console.log(req), it appears something?

  • yes, displays a list of properties and methods

1 answer

2


Friend, I’m assuming that this ajax code of yours is running on the same URL as your Node API, so at the url of your ajax you’re not passing the full path, only the /api/post, correct?
Well, if so, what must be happening is that you missed adding the body-parser module to your project.
To install go to the root folder of your project and run the command:

npm install body-parser --save

The --save parameter is not required, it serves to save this dependency in the file package.json.

After installing the module, you should import it into your project like this:

const express = require('express');

const app = express();
const bodyParser = require('body-parser');
const port = 3000;

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

const router = express.Router();
const path = require('path');

router.post('/api/post', (req, res) => {
  console.log(req.body);
  res.status(200).send('ok');
})
app.use(router);

/* Inicializa servidor */
app.listen(port);

In this example I am considering that the information will be sent using JSON, so the line app.use(bodyParser.json());.

To learn more about this module you can consult this link

  • It didn’t work, but it helped me. Instead of using the app = express() I used the const router. Then it was: router.use(bodyParser.urlencoded({Extended:true})); router.use(bodyParser.json());

  • True, to make it right there in my example I would only need to give one app.use(router); I will edit, if someone else needs it, in this example posted do not need another file to start just give the command node app.js (or the name you want for the file . js) . Thank you for warning

  • Thank you Murilo!

Browser other questions tagged

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