How to use the http response end method in node.js?
In Node.js, the http.response.end() method is used to complete a response and send data to the client. It takes an optional parameter to specify the data to be sent.
Here is a simple example demonstrating how to use the http.response.end() method.
const http = require('http');
// 创建一个HTTP服务器
const server = http.createServer((req, res) => {
// 设置响应头
res.writeHead(200, {'Content-Type': 'text/plain'});
// 向客户端发送数据
res.end('Hello, World!');
});
// 监听端口
server.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
In the example above, when the client sends a request, the server responds with a text saying “Hello, World!” and then calls the res.end() method to finish the response after sending the data.