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.
Node.js Basic HTTP Server
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.
Note: We aim to make learning easier by sharing top-quality tutorials, but please remember that tutorials may not be 100% accurate, as occasional mistakes can happen. Once you've mastered the language, we highly recommend consulting the official documentation to stay updated with the latest changes. If you spot any errors, please feel free to report them to help us improve.