Node.js Basic HTTP Server

Node.js allows you to create web servers and APIs quickly. This tutorial demonstrates how to set up a basic HTTP server using the built-in `http` module.

1. What is an HTTP Server?

An HTTP server is a software application that serves content over the HTTP protocol. It listens for incoming HTTP requests and sends back responses. Node.js has a built-in `http` module that allows you to create an HTTP server.

2. Setting Up the Basic HTTP Server

To create a basic HTTP server in Node.js, follow these steps:

const http = require('http');

const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('Hello, Node.js!');
});

server.listen(3000, '127.0.0.1', () => {
    console.log('Server running at http://127.0.0.1:3000/');
});

This code creates an HTTP server that responds with "Hello, Node.js!" when accessed.

3. Running the Server

Once your server script is ready, you can run the server with the following command in your terminal:

node app.js

Visit http://localhost:3000 in your browser to see the response.

4. Understanding the Code

The `http.createServer` method creates an HTTP server. Inside the callback function, `req` represents the incoming request, and `res` represents the response. We set the status code to 200, which means OK, and the `Content-Type` header to `text/plain`. Finally, we call `res.end()` to send the response back to the client.

5. Testing Your Server

Once the server is running, try accessing it from different browsers or using tools like Postman to test the response. You should see "Hello, Node.js!" displayed in your browser.

6. Conclusion

This basic HTTP server is the foundation of more complex Node.js applications. With Node.js, you can build scalable, fast, and efficient web servers.

0 Interaction
182 Views
Views
20 Likes
×
×
🍪 CookieConsent@Ptutorials:~

Welcome to Ptutorials

Note: We aim to make learning easier by sharing top-quality tutorials.

We kindly ask that you refrain from posting interactions unrelated to web development, such as political, sports, or other non-web-related content. Please be respectful and interact with other members in a friendly manner. By participating in discussions and providing valuable answers, you can earn points and level up your profile.

$ Allow cookies on this site ? (y/n)

top-home