Search code examples
javascriptnode.jsmongodbexpresspostman

Postman show up infinite "Sending request..." on my nodeJS MongoDB application


this is my entire code of my chatbot application

const express = require('express');
const app = express();
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const bodyParser = require('body-parser'); 
const dbName = "chatbotdb";

const jsonParser = bodyParser.json();
const urlencodedParser = bodyParser.urlencoded({extended: false});

app.use(jsonParser);
app.use(urlencodedParser);

const MongoConnection = (callback) =>{

    //creating connection to MongoDB database with connect() method which returns a promise
    MongoClient.connect('mongodb://localhost:27017/chatbotdb') //pass the DB along with connection-URL
    .then(client=>{
        console.log("Connected");
        db = client.db();  //fetch DB
        callback();
     })
    .catch(err=>{
        console.log(err);
     });
}



app.post('/insert', urlencodedParser, function(req, res){
    let objJson = {};
    if(req.body.code_user) objJson.code_user = req.body.code_user; else objJson.code_user = 0;
    if(req.body.code_session) objJson.code_session = req.body.code_session; else objJson.code_session = 0;
    if(req.body.code_current) objJson.code_current = req.body.code_current; else objJson.code_current = cod();
    if(req.body.code_relation) objJson.code_relation = req.body.code_relation; else objJson.code_relation = 0;
    if(req.body.code_before) objJson.code_before = req.body.code_before; else objJson.code_before = 0;
    if(req.body.input) objJson.input = req.body.input; else objJson.input = '';
    if(req.body.output) objJson.output = req.body.output; else objJson.output ='Desculpe, mas não entendi';

    insertData(objJson, function(result){
        res.send(result);
    })
});

function cod(){
    const data = new Date();
    const ano = data.getFullYear();
    const mes = data.getMonth();
    const dia = data.getDate();
    const hora = data.getHours();
    const minuto = data.getMinutes();
    const segundo = data.getSeconds();
    const milisegundos = data.getMilliseconds();
    const result = parseInt(Number(ano+''+mes+''+dia+''+hora+''+minuto+''+segundo+''+milisegundos)/2);
    return result;
}

app.post('/update', urlencodedParser, function(req, res){
    let objJson = {};
    if(req.body.code_user) objJson.code_user = req.body.code_user;
    if(req.body.code_session) objJson.code_session = req.body.code_session; 
    if(req.body.code_current) objJson.code_current = req.body.code_current;
    if(req.body.code_relation) objJson.code_relation = req.body.code_relation;
    if(req.body.code_before) objJson.code_before = req.body.code_before; 
    if(req.body.input) objJson.input = req.body.input; 
    if(req.body.output) objJson.output = req.body.output; 

    updateData(objJson, function(result){
        res.send(result);
    })
});

app.post('/delete', urlencodedParser, function(req, res){
    let objJson = {};
    if(req.body.code_user) objJson.code_user = req.body.code_user; 
    if(req.body.code_session) objJson.code_session = req.body.code_session; 
    if(req.body.code_current) objJson.code_current = req.body.code_current;
    if(req.body.code_relation) objJson.code_relation = req.body.code_relation;
    if(req.body.code_before) objJson.code_before = req.body.code_before; 
    if(req.body.input) objJson.input = req.body.input; 
    if(req.body.output) objJson.output = req.body.output; 

    deleteData(objJson, function(result){
        res.send(result);
    });
    });

    app.post('/find', urlencodedParser, function(req, res){
        let objJson = {};
        if(req.body.code_user) objJson.code_user = req.body.code_user; 
        if(req.body.code_session) objJson.code_session = req.body.code_session; 
        if(req.body.code_current) objJson.code_current = req.body.code_current;
        if(req.body.code_relation) objJson.code_relation = req.body.code_relation; 
        if(req.body.code_before) objJson.code_before = req.body.code_before; 
        if(req.body.input) objJson.input = req.body.input; 
        if(req.body.output) objJson.output = req.body.output; 
    
        findData(objJson, function(result){
            res.send(result);
        });
        });

const insertData = function(objJson, callback){
    const collection = db.collection('chatbot');
    collection.insertOne(objJson, function(err, result){
        assert.equal(null,err);
        callback(result);
    });
}

const updateData = function(objJson, callback){
    const collection = db.collection('chatbot');
    const code_current = objJson.code_current;
    collection.updateOne({code_current: code_current}, {$set: objJson} , function(err, result){
        assert.equal(null,err);
        callback(result);
    });
}

const deleteData = function(objJson, callback){
    const collection = db.collection('chatbot');
    collection.deleteOne(objJson,  function(err, result){
        assert.equal(null,err);
        callback(result);
    });
}


const findData = function(objJson, callback){
    const collection = db.collection('chatbot');
    collection.find(objJson).toArray(function(err, result){
        assert.equal(null,err);
        callback(result);
    });
}

MongoConnection(()=>{

    app.listen(3000, () => {
        console.log(`Database running & Listening on port: 3000`);
    })

})

app.get('/question', urlencodedParser, function(req, res){
    let objJson = {};
    if(req.query.code_user) objJson.code_user = Number(req.query.code_user); else objJson.code_user = 0;
    if(req.query.code_session) objJson.code_session = Number(req.query.code_session); else objJson.code_session = 0;
    if(req.query.code_before) objJson.code_before = Number(req.query.code_before); else objJson.code_before = 0;
    if(req.query.input) objJson.input = req.query.input; else objJson.input = '';

    questionData(objJson, function(result){
        res.send(result);
    });
});

const questionData = function(objJson, callback){
    const collection = db.collection('chatbot');
    collection.find(objJson).toArray(function(err, result){
        assert.equal(null,err);
        if(result.length<=0){
            collection.find({code_user:objJson.code_user}).toArray(function(err, result){
                assert.equal(null,err);
                result = nlp(objJson.input, result);
                callback(result);
            });
         } else callback(result);
        
    });
}

const nlp = function(question, array){
    let originalQuestion = question.toString().trim();
    let findInput = 0;
    let findIndex = 0;
    for(let i=0; i<array.length; i++){
        question = question.toString().trim();
        let input = array[i].input.toString().trim()
        if(input.length<=0) input = array[i].output.toString.trim();
        question = question.normalize('NFD').replace(/[\u0300-\u036f]/g,'').toLowerCase();
        input = input.normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase();
        question = question.replace(/[^a-zA-Z0-9\s]/g, '');
        input = input.replace(/[^a-zA-Z0-9\s]/g);

        let tokenizationQuestion = question.split(' ');
        let tokenizationInput = input.split(' ');

        tokenizationQuestion = tokenizationQuestion.map(function(e){
            if(e.length>3) return e.substr(0, e.length-3); else return e;
        });
        tokenizationInput = tokenizationInput.map(function(e){
            if(e.length>3) return e.substr(0, e.length-3); else return e;
        });
        let words = 0;
        for(let x=0; x<tokenizationQuestion.length; x++){
            if(tokenizationInput.indexOf(tokenizationQuestion[x])>=0) words++;
        }
        if(words>findInput){
            findInput = words;
            findIndex = i;
        }
        }
        if(findInput>0) return[{
            "_id": array[findIndex]._id,
            "code_user":array[findIndex].code_user,
            "code_session": array[findIndex].code_session,
            "code_current": array[findIndex].code_current,
            "code_relation": array[findIndex].code_relation,
            "code_before": array[findIndex].code_before,
            "input": originalQuestion,
            "output": array[findIndex].output
        }];
        else return [{
            "_id": "0",
            "code_user":array[findIndex].code_user,
            "code_session": array[findIndex].code_session,
            "code_current": array[findIndex].code_current,
            "code_relation": array[findIndex].code_relation,
            "code_before": array[findIndex].code_before,
            "input": originalQuestion,
            "output": "Desculpe, mas não sei responder."
        }];
}

When i use postman to send my post and get requests, the crud works well and the collection is actually updated, deleted or inserted, but postman never sends me the response of my local server, it always sit infinitely on the message "Sending request..." and because of that, i cannot use my '/find' or my get method to search for specific items


Solution

  • Use this as a sample for the post, where i had to remove the unnecessary assert function and focus on checking for errors

       const express = require('express');
    const app = express();
    const MongoClient = require('mongodb').MongoClient;
    const bodyParser = require('body-parser');
    const dbName = "chatbotdb";
    
    const jsonParser = bodyParser.json();
    const urlencodedParser = bodyParser.urlencoded({ extended: false });
    
    app.use(jsonParser);
    app.use(urlencodedParser);
    
    let db;
    
    
    const MongoConnection = (callback) => {
        MongoClient.connect('mongodb://localhost:27017', { useNewUrlParser: true, useUnifiedTopology: true })
            .then(client => {
                console.log("Connected to database");
                db = client.db(dbName);
                callback();
            })
            .catch(err => {
                console.error('Failed to connect to the database', err);
                process.exit(1); 
            });
    };
    
    
    app.post('/insert', async function (req, res) {
        const objJson = {
            code_user: req.body.code_user || 0,
            code_session: req.body.code_session || 0,
            code_current: req.body.code_current || cod(),
            code_relation: req.body.code_relation || 0,
            code_before: req.body.code_before || 0,
            input: req.body.input || '',
            output: req.body.output || 'Desculpe, mas não entendi'
        };
    
        console.log('Received data for insert:', objJson);
    
        try {
            const result = await insertData(objJson);
            res.json(result);
        } catch (error) {
            res.status(500).json({ error: 'An error occurred during insert' });
        }
    });
    
    
    function cod() {
        const data = new Date();
        return parseInt(Number(data.getFullYear() + '' + (data.getMonth() + 1) + '' + data.getDate() + '' + data.getHours() + '' + data.getMinutes() + '' + data.getSeconds() + '' + data.getMilliseconds()) / 2);
    }
    
    
    const insertData = async function (objJson) {
        try {
            const collection = db.collection('chatbot');
            const result = await collection.insertOne(objJson);
            console.log('Insert Success:', result);
            return result; 
        } catch (error) {
            console.error('Insert Error:', error);
            throw new Error('An error occurred during insert');
        }
    }
    
    MongoConnection(() => {
        app.listen(3000, () => {
            console.log('Database connected & Server listening on port 3000');
        });
    });
    

    I changed the insert function to an asynchronous function so it can wait for the database operation to be done before returning to the client.

    In my quest to debug your code, i added try catch to log errors

    here is my postman response