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
if you only use console.log(req), it appears something?
– Luan Brito
yes, displays a list of properties and methods
– Felipe Coelho