簡體   English   中英

Node.js作為JSON轉發器

[英]Node.js as a JSON forwarder

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

你應該使用快遞 ,它會使它更容易。

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最有幫助,但我認為我的解決方案將同時使用http lib和express表示為3on,因為我非常喜歡它的簡單性......

所以對於那些感興趣的人,我的最終解決方案是兩者的組合:

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

非常好,整潔。 謝謝大家的幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM