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

相关推荐
SPC的存折6 分钟前
3、主从复制实现同步数据过滤
linux·运维·服务器
SPC的存折9 分钟前
openEuler 24.03 MariaDB Galera 集群部署指南(cz)
linux·运维·服务器·数据库·mysql
xcbrand11 分钟前
文旅行业品牌策划公司找哪家
大数据·运维·人工智能·python
SPC的存折22 分钟前
MySQL 8.0 分库分表
linux·运维·服务器·数据库·mysql
胡哈36 分钟前
MCP (Model Context Protocol) 原理与实战
node.js·mcp
风吹迎面入袖凉39 分钟前
【Redis】Redisson分布式锁原理
java·服务器·开发语言
cyber_两只龙宝43 分钟前
【Oracle】Oracle之DQL中WHERE限制条件查询
linux·运维·数据库·云原生·oracle
斌味代码1 小时前
Shell 性能监控:指标采集、告警规则与可视化大盘设计
运维
22信通小白1 小时前
USRP初学者使用手册(基础配置及bug记录)——Linux+Clion(单台X310收发)
linux·运维·c++·5g·bug·信息与通信
day day day ...2 小时前
MyBatis条件误写引发的查询条件污染分析与防范
java·服务器·tomcat