如何用Node.js构建一个HTTP服务器
这是我们在Node.js介绍中作为Node Hello World应用程序使用的HTTP网络服务器
const http = require('http')
const hostname = 'localhost'
const port = 3000
const server = http.createServer((req, res) => {
res.statusCode = 200
res.setHeader('Content-Type', 'text/plain')
res.end('Hello World\n')
})
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`)
})
让我们简单地分析一下。我们包括http 模块。
我们使用该模块来创建一个HTTP服务器。
该服务器被设置为在指定的主机名localhost ,端口3000 ,进行监听。当服务器准备好后,listen 回调函数被调用。
我们传递的回调函数是在每个请求进来时都要执行的函数。每当收到一个新的请求,request 事件被调用,提供两个对象:一个请求(一个 http.IncomingMessage对象)和一个响应(一个 http.ServerResponse对象)。
request 提供请求的细节。通过它,我们访问请求头和请求数据。
response 是用来填充我们要返回给客户端的数据的。
在本例中,我们用
我们将statusCode属性设置为200,以表示一个成功的响应。
我们还设置了Content-Type头。
res.setHeader('Content-Type', 'text/plain')
并且我们结束关闭响应,将内容作为参数添加到end() 。