2017-07-18 115 views
0

我的节点应用程序的路由文件夹中有两个文件,例如fetchCity.js和addNewDevice.js。我想将请求参数从addNewDevice.js转发到fetchCity.js并在addNewDevice.js文件中处理响应。我试过下面的代码,但没有工作。NodeJS中的请求转发

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)); 
      }); 
     }); 
    } 

回答

0

通过在node.js代码中使用http模块并按照以下伪代码发送请求来解决此问题。

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}); 
     });  
}); 
0

代替:

app.post('/fetchCityArea',function(req,res){ 
        console.log('Response from fetchCityArea is ' + JSON.stringify(res)); 
      }); 

使用:

res.redirect('/fetchCityArea'); 

原因:app.post( '/ someRoute')是一个HTTP监听模块不是一个http请求模块。而res.redirect是响应对象的一个​​函数,它会将负载重定向到传递给它的路由。

+0

我认为它会重定向用户和响应将被发送给用户。用户可以随时向/ fetchCityArea发送请求。但是,当他们向/ addNewDevice发送请求时,我需要在/ addNewDevice中处理/ fetchCityArea的响应。如果我错了,请纠正我。因为在服务器代码中使用重定向方法后,我没有找到如何获取响应对象。 –

+0

是的,你是对的。你是否也在app.post处理程序中处理请求? –

+0

是的,我想从/ addNewDevice发送请求到/ fetchCityArea,并且在收到响应后,我想在/ addNewDevice中进一步处理它。预期的行为与Java中的RequestDispatcher.forward方法类似。 –