javascript - Node.js 作为 JSON 转发器

标签 javascript json web-services node.js

我是 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);

关于javascript - Node.js 作为 JSON 转发器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7539715/

相关文章:

xml - 通过 Web 服务将文件作为字节数组发送时会产生多少额外开销?

javascript - ng-class 仅适用于 ng-repeat angularjs 中的当前范围

json - 将 Parquet 从 AWS Kinesis firehose 写入 AWS S3

javascript - 用数组键/值替换字符

java - 使用 JSON 获取数据

arrays - 使用 ruby​​ 以 DRY 方式提取散列中的值

java - 不用 Maven 构建动态 Web 项目

ios - 从服务中获取值

javascript - 使用 jQuery 设置动态 Meta 标签和 Open Graph 标签

javascript - 原型(prototype)函数可以访问局部变量吗?