乐闻世界logo
搜索文章和话题

How to include HTTP server in the Node module?

1个答案

1

Creating an HTTP server in Node.js primarily relies on the built-in http module. Here are the steps to create a basic HTTP server:

1. Import the HTTP Module

First, import the built-in http module in your Node.js file.

javascript
const http = require('http');

2. Create the Server

Use the http.createServer() method to create an HTTP server instance. This method accepts a callback function that executes for each HTTP request. The callback function has two parameters: req (request object) and res (response object).

javascript
const server = http.createServer((req, res) => { res.statusCode = 200; // Set the response status code res.setHeader('Content-Type', 'text/plain'); // Set the response header res.end('Hello, World!\n'); // Send the response });

3. Listen on a Port

The server must listen on a port to receive client requests. Use the server.listen() method to specify the port. You can also provide a callback function that executes after the server successfully binds to the specified port.

javascript
const port = 3000; // Choose any unused port server.listen(port, () => { console.log(`Server running at http://localhost:${port}/`); });

Complete Example Code

Combine the above steps into a full Node.js script to start a simple HTTP server:

javascript
const http = require('http'); const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello, World!\n'); }); const port = 3000; server.listen(port, () => { console.log(`Server running at http://localhost:${port}/`); });

Test the Server

Run this script and access http://localhost:3000 in your browser. You should see "Hello, World!" displayed on the page.

This example demonstrates how to use Node.js's http module to quickly set up an HTTP server. Such servers are ideal for API development, local testing, and other lightweight applications. For more complex applications, consider using a robust framework like Express.js to handle routing, middleware, and advanced features.

2024年8月6日 00:18 回复

你的答案