Youssef
Youssef

Reputation: 13

node.js post method req.body undefined even with body-parser

Hello guys I am working with node js to use dialogflow chat bot ,

I am trying to get parameters from http request post methode

I used postman for that and yes I did set up the content type to json in the header , I have the following code for my request body :

{
"text":"hello"
}

and the following link http://localhost:5000/api/df_text_query

I have the following index.js file :

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


const app = express();

require('./routes/dialogFlowRoutes')(app);


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

app.get('/',(req , res)=>{

res.send({'hello':'Johnny'});

});


const PORT = process.env.port || 5000;

app.listen(PORT);

this my dialogflowRoutes.js file :

const dialogflow = require('dialogflow');
 const config = require('../config/keys');
 const sessionClient = new dialogflow.SessionsClient();
 const sessionPath = sessionClient.sessionPath(config.googleProjectID, config.dialogFlowSessionID);
    module.exports = app => {
    app.get('/', (req, res) => {
        res.send({ 'hello': 'world!' })
        
    });
    app.post('/api/df_text_query', async (req, res) => {
        console.log(req.body)
        const request = {
            session: sessionPath,
            queryInput: {
                text: {
                    text: req.body.text,
                    languageCode: config.dialogFlowSessionLanguageCode
                }
            }
        };

    let responses = await sessionClient
        .detectIntent(request);

    res.send(responses[0].queryResult)
    });

app.post('/api/df_event_query', (req, res) => {
    res.send({ 'do': 'event query' })
});
}

this is the error I get when I send the following request

dialogFlowRoutes.js:17
                    text: req.body.text,
                                   ^

TypeError: Cannot read property 'text' of undefined

Upvotes: 1

Views: 759

Answers (1)

Anastazy
Anastazy

Reputation: 4756

Order in which you initialize middleware matters.

You must parse body before you act on it. Move your routing middleware after you initialize bodyParser, like below:

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }))
require('./routes/dialogFlowRoutes')(app);

Upvotes: 1

Related Questions