How to Create HTTP Server With Node.js

hasib787

Md. Masud Rana

Posted on March 18, 2020

How to Create HTTP Server With Node.js

http-Server
Creating a simple proxy server in node.js

Installation:

Globally via npm

brew install http-server

Running on-demand: npx http-server [path] [options]

As a dependency in your npm package: npm install http-server

Usage: http-server [path] [options]

[path] defaults to ./public if the folder exists, and ./ otherwise.

Now you can visit http://localhost:8080 to view your server

Note: Caching is on by default. Add -c-1 as an option to disable caching.

Code-

let http = require('http');

http.createServer(onRequest).listen(3000);

function onRequest(client_request, client_res) {
console.log('serve: ' + client_request.url);

let options = {
hostname: 'www.google.com',
port: 80,
path: client_request.url,
method: client_request.method,
headers: client_request.headers
};

let proxy = http.request(options, function (res) {
client_res.writeHead(res.statusCode, res.headers)
res.pipe(client_res, {
end: true
});
});

client_req.pipe(proxy, {
end: true
});
}

More details-https://github.com/Hasib787/http-Server

💖 💪 🙅 🚩
hasib787
Md. Masud Rana

Posted on March 18, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related