A simple example of a web server is written with Node.js

Amol Gunjal
1 min readApr 27, 2020

--

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.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Amol Gunjal
Amol Gunjal

Responses (1)

Write a response