您的位置:宽带测速网 > 编程知识 > node.js中的http.response.end方法怎么使用

node.js中的http.response.end方法怎么使用

2025-06-17 15:30来源:互联网 [ ]

在Node.js中,http.response.end()方法用于结束响应,并向客户端发送数据。它接受一个可选的参数用于指定要发送的数据。

下面是一个简单的示例,展示了如何使用http.response.end()方法:

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');});

在上面的示例中,当客户端发送请求时,服务器会响应一个Hello, World!的文本,并在发送完数据后调用res.end()方法来结束响应。