A simple example of a web server is written with Node.js
The HTTP core module is a key module to Node.js networking.
To use HTTP server and client need require(‘http’)
const http = require(‘http’);
To set the host and port, use the constant.
const hostname = ‘127.0.0.1’;
const port = 3000;
createServer is creating an instance of an HTTP server.
const server = http.createServer( (req, res) => {
res.statusCode = 200;
res.setHeader(‘Content-Type’, ‘text/plain’);
res.end(‘Hey, Connected !\n’);
} );
Create a server that listens on port 3000 of your computer.
When port 3000 get accessed, write “Hey, Connected !” back as a response:
server.listen( port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}`);
} );
connect.js
const http = require(‘http’);
const hostname = ‘127.0.0.1’;
const port = 3000;const server = http.createServer( (req, res) => {
res.statusCode = 200;
res.setHeader(‘Content-Type’, ‘text/plain’);
res.end(‘Hey, Connected!\n’);
} );server.listen( port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}`);
} );
Run connect.js,
$ node connect.js
Output like this should appear in the terminal:
Server running at http://127.0.0.1:3000/
Now, open any preferred web browser and visit http://127.0.0.1:3000.
If the browser displays the string Hey, Connected!, that indicates the server is working.