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

相关推荐
codingWhat16 小时前
整理「祖传」代码,就是在开发脚手架?
前端·javascript·node.js
ServBay16 小时前
Node.js、Bun 与 Deno,2026 年后端运行时选择指南
node.js·deno·bun
码路飞1 天前
Node.js 中间层我维护了两年,这周终于摊牌了——成本账单算完我人傻了
node.js
碳基沙盒1 天前
OpenClaw 多 Agent 配置实战指南
运维
None3212 天前
【NestJs】使用Winston+ELK分布式链路追踪日志采集
javascript·node.js
Dilettante2582 天前
这一招让 Node 后端服务启动速度提升 75%!
typescript·node.js
Mr_li3 天前
NestJS 集成 TypeORM 的最优解
node.js·nestjs
UIUV3 天前
node:child_process spawn 模块学习笔记
javascript·后端·node.js
Sinclair3 天前
简单几步,安卓手机秒变服务器,安装 CMS 程序
android·服务器
前端付豪4 天前
Nest 项目小实践之注册登陆
前端·node.js·nestjs