温馨提示×

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

小亿
88
2024-03-08 15:39:26
栏目: 编程语言

在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()方法来结束响应。

0