How to build an HTTP server in Node.js

It's very easy to set up a simple HTTP server in Node.js. Here is a basic example of how to create a simple HTTP server using Node.js:

//Import the http module const http = require('http');

//Create an HTTP server

const server = http.createServer((req, res) => {

//Set response headers

res.writeHead(200, {'Content-Type': 'text/plain'});

//Send response content

res.end('Hello, World!\n');

});

// Listen to a specific port

const port = 3000;

server.listen(port, () => {

console.log(`Server is running on http://localhost:${port}`);

});

In this example, we use Node.js's http module to create an HTTP server. The createServer method accepts a callback function, which will be called every time there is a request. In the callback function, we can set the response headers, send the response content, and end the response using res.end().

Then, we use the listen method to specify the port the server listens on. In this example, the server will listen on port 3000. When the server is started, you can visit http://localhost:3000 in your browser and you should see "Hello, World!".

おすすめ

転載: blog.csdn.net/JttiSEO/article/details/132452204