javascript – Node.js作为JSON转发器

前端之家收集整理的这篇文章主要介绍了javascript – Node.js作为JSON转发器前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我是Node.js的新手,但我想将它用作一个快速的Web服务器,它只需要一个请求uri,然后在一个返回 JSON流的内部服务上运行查询.

即像这样的东西:

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.我希望这很容易做到,但我没能在网上找到一些例子,因为他们似乎都使用旧的API版本,所以我在错误后得到错误.

是否有人能够提供上述与新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);
原文链接:https://www.f2er.com/js/157838.html

猜你在找的JavaScript相关文章