Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js as a JSON forwarder

I'm new to Node.js but I wanted to use it as a quick web server which would simply take in a request uri and then run a query on an internal service which returns a JSON stream.

I.e. something like this:

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

I'm using the newest stable version of node.js - version 0.4.12. I was hoping this would be very easy to do however, I havent been able to find some examples on the net as they all seem to use an old API version so I'm getting error after error.

Would anyone be able to provide a code solution to the above that works with the new Node APIs?

Thanks!

like image 643
NightWolf Avatar asked Sep 24 '11 14:09

NightWolf


People also ask

Does JSON work in node JS?

JSON is one of the most common types of data you'll work with in Node, and being able to read and write JSON files is very useful. You've learned how to use fs. readFile and fs. writeFile to asynchronously work with the filesystem, as well as how to parse data to and from JSON format, and catch errors from JSON.

Can I import a JSON file in Nodejs?

Update: Since Node. js 17. 5 , it's possible to leverage import assertions in ECMAScript modules to import JSON files. /* Experimental JSON import is supported since Node.


1 Answers

here is a code that should explain your task:

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);
like image 150
Nican Avatar answered Sep 20 '22 19:09

Nican