NodeJS中的请求转发
Request forwarding in NodeJS
我的节点应用程序的路由文件夹中有两个文件,如 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));
});
});
}
而不是:
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 是响应对象的函数,它将有效负载重定向到传递给它的路由。
通过在 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});
});
});
我的节点应用程序的路由文件夹中有两个文件,如 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));
});
});
}
而不是:
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 是响应对象的函数,它将有效负载重定向到传递给它的路由。
通过在 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});
});
});