Search code examples
node.jsexpresswebserverresponse

how to catch a server response?


There is a client wich is sending requests to my webserver. This Server should answer with data or an specific code, for example 117 (yes this a halo reference :D) Now I need access to the responded data or code. How could I realize this? I found nothing similar here at stackoverflow, may you can help.

Client example:

function sendRequest() {
        var options = {
            host: 'localhost',
            port: 1309,
            path: '/examplePath?param='+param,
            param: "example"
        };
        http.get(options, function(resp){
            resp.on('data', function(chunk){
                console.log("chunk :",chunk);
            });
        }).on("error", function(err){
            console.log("Error: " + err.message);
        });

}

Answering Server:

function examplePathFunction(req,res) {

    if(condition) {
        //TODO Server must answer with data
    } else {
        //TODO Server must answer with status 117
    }
}

Would : res.end(date/code); solve my problem? And how do I catch this response ?


Solution

  • I think you're looking for:

    function examplePathFunction(req, res, next) {
    
    if(req.body.data) {
        res.status(200).send({ data: req.body.data });
        return next();
     } else {
        res.status(117);
        return next();
       }
    }
    

    Though if you're trying to send data through params, look there rather than the request body.

    Read more about the Express API: http://expressjs.com/en/api.html#req