HTTP 协议实战 - Node篇| 青训营

79 阅读1分钟

在Node.js中,我们可以使用http模块来创建一个HTTP服务器。下面是一个简单的示例:

const http = require('http');

// 创建服务器
const server = http.createServer((req, res) => {
  // 设置响应头
  res.setHeader('Content-Type', 'text/plain');
  
  // 处理请求
  if (req.url === '/') {
    res.end('Hello, World!');
  } else if (req.url === '/about') {
    res.end('About Page');
  } else {
    res.end('404 Not Found');
  }
});

// 监听端口
server.listen(3000, 'localhost', () => {
  console.log('Server is running at http://localhost:3000/');
});

在这个例子中,我们首先导入了Node.js的http模块。然后使用http.createServer()方法创建了一个HTTP服务器。这个方法接受一个回调函数作为参数,该回调函数会在每个请求到达时被调用。

回调函数有两个参数:reqres,分别代表请求和响应对象。我们可以使用这两个对象来处理请求和发送响应。

在回调函数中,我们首先使用res.setHeader()方法设置响应头的Content-Type字段为text/plain,表示响应的内容类型为纯文本。

然后,我们通过req.url来判断请求的路径。如果路径是'/',则发送'Hello, World!'作为响应。如果路径是'/about',则发送'About Page'作为响应。其他路径则发送'404 Not Found'作为响应。

最后,我们调用server.listen()方法来监听端口,并在服务器启动后打印出服务器地址。

要运行这个例子,可以使用以下命令:

node server.js

然后在浏览器中访问http://localhost:3000/http://localhost:3000/about,你应该能够看到相应的响应。

这只是一个简单的例子,实际上,我们可以使用http模块来处理更复杂的HTTP请求和响应。例如,我们可以解析请求体、处理表单数据、发送文件等。