1

I'm trying to understand how RESTful APIs work. I'm trying to route a POST request with ExpressJS. My problem is that req.body.name always returns undefined. In other words, I can't access data from the body of the HTTP request.

Here is the request I'm sending using Postmanenter image description here

And here is the error message send in the response enter image description here

I've read through several articles and I understand that one must use some additional software (a.k.a middleware) to make the request body readable to Express (i.e parse the request). However I don't really understand why this is the case. Why can't I just access request.body.name directly?

Here is my code

const express = require('express');
const app = express();

app.get('/', (req,res)=>{
    console.log('Im in the index');
    res.send('Index page');
});

app.get('/parameterRoute/:id', (req,res)=>{
    console.log('Im in parameterRoute');
    res.send(req.params.id);
});

// This is the problem
app.post('/postRoute',(req,res) =>{

    res.send(req.body.name);
});
Zaham2
  • 337
  • 1
  • 4
  • 11
  • 3
    Does this answer your question? [What does body-parser do with express?](https://stackoverflow.com/questions/38306569/what-does-body-parser-do-with-express) – SuleymanSah Dec 26 '19 at 11:49
  • It does clarify things a bit, though I'm still confused as to why the body isn't parsed in the first place. Wouldn't it be better to make the body directly accessible than to go through the trouble of adding middleware? – Zaham2 Dec 26 '19 at 11:56
  • 2
    That's another story, and already discussed in the [comments](https://stackoverflow.com/a/43626891/11717458) – SuleymanSah Dec 26 '19 at 11:58
  • 3
    Read this https://expressjs.com/en/resources/middleware/body-parser.html. – Prabhjot Singh Kainth Dec 26 '19 at 12:18
  • I found the article on "anatomy of a HTTP request" in Node.js which is linked in the body-parser docs that Prabhjot linked useful. Particularly this part - https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/#request-body – cdimitroulas Dec 26 '19 at 13:14
  • 1
    Request's body does not have to be JSON. it can be text, form and other types. You need body-parser to tell express what type is the body. The body-parser reads the Content-Type header and checks if it matches your configuration. Then it parses the body into req.body object. – dima golovin Dec 26 '19 at 13:45

1 Answers1

0

Add the line:

app.use(express.urlencoded());

after the line

const app = express();

Done...for me the problem was solve after doing this.

Brad
  • 159,648
  • 54
  • 349
  • 530
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-ask). – Community Sep 21 '21 at 04:25