在NodeJS

时间:2017-07-18 06:56:47

标签: node.js request forward

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

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

2 个答案:

答案 0 :(得分: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是响应对象的函数,它将有效负载重定向到传递给它的路由。

答案 1 :(得分: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});
        });     
});