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

How can you create a simple HTTP server in Node.js?

1个答案

1

Creating a simple HTTP server in Node.js is quite straightforward. Node.js includes an http module, which we can use to create a server. Here are the basic steps, along with a simple example:

Step 1: Import the HTTP Module

First, we need to import the http module provided by Node.js, which offers methods for creating a server.

javascript
const http = require('http');

Step 2: Create the Server

Use the http.createServer() method to create a server. This method accepts a callback function that is invoked every time an HTTP request arrives.

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

Step 3: Listen on a Port

Make the server listen for HTTP requests. Typically, during local development, we use port 3000 or another non-reserved port.

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

Complete Code Example

Combining the above steps, we can get a complete Node.js HTTP server implementation:

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}/`); });

How to Run

You can save this code as a .js file, such as server.js. Then, run it from the command line using Node.js:

bash
node server.js

Open your browser and visit http://localhost:3000/; you should see a page displaying "Hello, World!".

The above steps outline how to create a simple HTTP server in Node.js. This method is ideal for learning and experimentation. For more complex production environments, we typically use frameworks like Express to handle advanced features and routing requirements.

2024年8月8日 02:48 回复

你的答案