Node.js 网站服务器开发


第一课时实操:创建第一个 Node.js 服务器

实训目标

  • 理解服务器基本概念
  • 能够使用 Node.js 创建简单的 HTTP 服务器
  • 掌握请求与响应的基本流程

源码示例

js 复制代码
// 引入 http 模块
const http = require('http');

// 创建服务器
const server = http.createServer((req, res) => {
  // 设置响应头
  res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
  // 发送响应内容
  res.end('<h1>欢迎访问我的第一个 Node.js 服务器!</h1>');
});

// 监听端口
server.listen(3000, () => {
  console.log('服务器运行在 http://localhost:3000');
});

操作步骤

  1. 新建 server.js 文件,粘贴上述代码
  2. 在终端中运行:node server.js
  3. 浏览器访问 http://localhost:3000,查看输出结果

第二课时实操:处理不同请求与响应

实训目标

  • 理解 HTTP 请求方法(GET/POST)
  • 能根据 URL 返回不同内容
  • 掌握设置状态码与响应头

源码示例

js 复制代码
const http = require('http');
const url = require('url');

const server = http.createServer((req, res) => {
  const pathname = url.parse(req.url).pathname;
  const method = req.method;

  // 设置响应头
  res.setHeader('Content-Type', 'text/html; charset=utf-8');

  // 根据路径返回不同内容
  if (pathname === '/' && method === 'GET') {
    res.writeHead(200);
    res.end('<h1>首页</h1><a href="/about">关于我们</a>');
  } else if (pathname === '/about' && method === 'GET') {
    res.writeHead(200);
    res.end('<h1>关于我们</h1><p>这是关于页面</p>');
  } else if (pathname === '/submit' && method === 'POST') {
    // 模拟处理 POST 请求
    let body = '';
    req.on('data', chunk => body += chunk);
    req.on('end', () => {
      res.writeHead(200);
      res.end(`<p>收到 POST 数据:${body}</p>`);
    });
  } else {
    res.writeHead(404);
    res.end('<h1>页面不存在</h1>');
  }
});

server.listen(3000, () => {
  console.log('服务器运行在 http://localhost:3000');
});

操作步骤

  1. 新建 app.js,粘贴代码并运行
  2. 访问 http://localhost:3000/about 测试 GET 请求
  3. 使用 Postman 或 HTML 表单测试 /submit 的 POST 请求

扩展练习(可选)

实训目标

  • 获取并打印请求头信息
  • 设置不同的 Content-Type 返回 JSON 或图片链接

示例代码片段:

js 复制代码
// 获取请求头
console.log(req.headers['user-agent']);

// 返回 JSON
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: 'Hello JSON' }));

相关推荐
Xの哲學1 小时前
深入剖析Linux文件系统数据结构实现机制
linux·运维·网络·数据结构·算法
深圳市恒讯科技1 小时前
Linux 文件权限指南:chmod 755、644、drwxr-xr-x 解析
linux·服务器·xr
Wpa.wk1 小时前
性能测试工具 - JMeter工具组件介绍二
运维·经验分享·测试工具·jmeter·自动化·json
朝阳5811 小时前
Ubuntu 22.04 安装 Fcitx5 中文输入法完整指南
linux·运维·ubuntu
xingzhemengyou11 小时前
Linux taskset指令设置或查看进程的 CPU 亲和性
linux·服务器
开开心心就好1 小时前
图片格式转换工具,右键菜单一键转换简化
linux·运维·服务器·python·django·pdf·1024程序员节
永远在Debug的小殿下1 小时前
wsl安装Ubuntu and ROS2
linux·运维·ubuntu
❀͜͡傀儡师1 小时前
docker一键部署HFish蜜罐
运维·docker·容器
DO_Community1 小时前
DigitalOcean容器注册表推出多注册表支持功能
服务器·数据库·docker·kubernetes
其美杰布-富贵-李1 小时前
深度学习中的 tmux
服务器·人工智能·深度学习·tmux