Search code examples
node.jsrequestforward

Request forwarding in NodeJS


I have two files in my route folder of node application like fetchCity.js and addNewDevice.js. I want to forward the request parameters from addNewDevice.js to fetchCity.js and process the response in addNewDevice.js file. I tried following code but is not working.

    var express = require('express');

    module.exports = function(app){
        var cors = require('cors');
        var coptions = {
            "origin": "*",
            "methods": "GET,HEAD,PUT,POST,OPTIONS",
            "preflightContinue": false,
            "allowedHeaders":['Content-Type']
        }
        var db = require('./dbclient');
        var bodyParser = require('body-parser');
        app.use(cors(coptions));
        app.use(bodyParser.json());
        app.use(bodyParser.urlencoded({extended:true}));
        app.post('/newBinDevice', function(req, res, next) {

            var did = req.body.deviceid;
            var sver = req.body.swver;
            var city = req.body.city;
            var circle = req.body.circle;
            app.post('/fetchCityArea',function(req,res){
                    console.log('Response from fetchCityArea is ' + JSON.stringify(res));
            });
        });
    }

Solution

  • Solved the issue by using http module in node.js code and sending the request as per below pseudo code.

    var http = require('http');
    
    app.post('/abc',function(req,res) {
            http.get(url,function(resp){ 
                    resp.on('data',function(buf){//process buf here which is nothing but small chunk of response data});
                    resp.on('end',function(){//when receiving of data completes});
            });     
    });