Node.js作为JSON转发器

我是Node.js的新手,但是我想用它作为一个快速的web服务器,它只需要一个请求uri,然后在返回一个JSONstream的内部服务上运行一个查询。

即这样的事情:

http.createServer(function(request, response) { var uri = url.parse(request.url).pathname; if(uri === "/streamA") { //send get request to internal network server http://server:1234/db?someReqA -->Returns JSON ....? //send response to requestor of the JSON from the above get ....? } else if(uri === "/streamB") { //send get request to internal network server http://server:1234/db?someReqB -->Returns JSON ....? //send response to requestor of the JSON from the above get....? }.listen(8080); 

我正在使用最新的稳定版本的node.js – 版本0.4.12。 我希望这会很容易做,但是我还没有能够find一些在网上的例子,因为他们似乎都使用旧的API版本,所以我得到错误后的错误。

任何人都可以提供上述的代码解决scheme,与新的Node API一起工作?

谢谢!

这里是一个代码,应该解释你的任务:

 var http = require('http'); var url = require('url') var options = { host: 'www.google.com', port: 80, path: '/' //Make sure path is escaped }; //Options for getting the remote page http.createServer(function(request, response) { var uri = url.parse(request.url).pathname; if(uri === "/streamA") { http.get(options, function(res) { res.pipe( response ); //Everything from the remote page is written into the response //The connection is also auto closed }).on('error', function(e) { response.writeHead( 500 ); //Internal server error response.end( "Got error " + e); //End the request with this message }); } else { response.writeHead( 404 ); //Could not find it response.end("Invalid request"); } }).listen(8080); 

你应该使用快递 ,这将使它更容易。

 var app = express.createServer(); app.get('/json1', function(req, res){ var json // = res.send(json); }); app.get('/json2', function(req, res){ var json // = res.send(json); }); app.listen(8000); 

好吧,因为这个问题有一些增加票,它似乎也有其他人也对它感兴趣。 虽然Nican的回答对于获得实际的JSON最有帮助,但我决定我的解决scheme将使用http lib和express,正如我所build议的,因为我真的很喜欢它的简单性。

所以对于那些感兴趣的人来说,我的最终解决scheme是两者的结合:

 var http = require("http"), url = require("url"); var app = require('express').createServer(); app.listen(9898); var query = {"SQL" : "SELECT * FROM classifier_results_summary"}; var options = { host: 'issa', port: 9090, path: '/db?'+ escape(JSON.stringify(query)) }; //Options for getting the remote page app.get('/stream/:id', function(req, res){ //console.log(options.path); http.get(options, function(response) { response.pipe( res ); //Everything from the remote page is written into the response //The connection is also auto closed }).on('error', function(e) { response.writeHead( 500 ); //Internal server error response.end( "Got error " + e); //End the request with this message }); }); 

非常好,整洁。 感谢所有的帮助。