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

相关推荐
竹林8181 小时前
在Web3前端用Node.js子进程批量校验钱包,我踩了这些性能与安全的坑
javascript·node.js
w-w0w-w1 小时前
Unix网络编程
服务器·网络·unix
曾经拒绝刘亦菲1 小时前
Clamav在麒麟V10离线安装指南
运维
志栋智能1 小时前
超自动化巡检:应对复杂IT环境的必然选择
运维·网络·安全·web安全·自动化
li星野2 小时前
[特殊字符] Linux/嵌入式Linux面试模拟卷
linux·运维·面试
肠胃炎2 小时前
挂载方式部署项目
服务器·前端·nginx
mldlds2 小时前
windows手动配置IP地址与DNS服务器以及netsh端口转发
服务器·windows·tcp/ip
一直都在5723 小时前
深入理解 synchronized:到底锁的是谁?
运维·服务器
RisunJan3 小时前
Linux命令-mkbootdisk(可建立目前系统的启动盘)
linux·运维·服务器
Sst的头号粉丝3 小时前
Docker——compose
运维·docker·容器