Express.js/Node.js Responses Before Query Finishes

142 views Asked by At

I have a local server that is fully functioning when POSTs and GETs are sent from Postman or chrome rest apps etc. However, whenever I send it from an ESP8266 it fails as it follows:

This is my server side code:

router.get('/', function (req, res) {
var person = req.query.id;
console.log("1");
Person.find({person: personID} ,function (err, station) {
    if(err) console.log(err.message);

    console.log("3");
    res.send('test');
    console.log("4");
});

console.log("2");
});

Lines below are from console when request is sent from Chrome.

1
2
3
4
GET /api?id=ABKWTltz6Ug 200 21.829 ms - -

And the lines below are from console when request is sent from ESP8266.

1
2
GET /api?id=ABKWTltz6Ug - - ms - -
3
4

As you may notice logs 3 and 4 are after GET response line. My ESP8266 TCP connection lines match the HTTP Message Format:

GET /api HTTP/1.1
Host: *SERVER_IP_ADDRESS*

The problem raised when we switched from PHP to NodeJS backend server. ESP8266 used to connect and operate without problems back then. And FYI, everything also works fine if I remove the Person.find code block and move the res.send('test'); outside.

Another freshly written backend code to hopefully spot the error is below. This is the whole code. Which also returns the same error I've mentioned earlier above:

var express = require('express');
var app = express();
var router = express.Router();
var mongoose = require('mongoose');
var morgan = require('morgan');


app.use(morgan('dev'));

mongoose.connect('mongodb://localhost/test');


//mongoose.Promise = Promise;
var Test = mongoose.model('Test', { name: String });

router.get('/test', function (req, res) {

    console.log("1");
    var test1 = new Test({
      name: "Name"
    });

    var query = test1.save();

    query.then(function (doc) {
        res.send('1').end();
        console.log('3');
    });

    console.log("2");
});

app.use('/api', router);

var port = 9000;
app.listen(port,function(){
    console.log('server started on', port);

});
0

There are 0 answers