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

相关推荐
米丘3 小时前
vite8 vite preview 命令做了什么?
node.js·vite
blanks202020 小时前
生成 公钥私钥 笔记
node.js
糖拌西瓜皮2 天前
Java开发者视角:深入理解Node.js异步编程模型
java·后端·node.js
大树883 天前
金刚石散热越强,管路越先见顶
大数据·运维·服务器·人工智能·ai
摇滚侠3 天前
Linux CentOS7 rpm 安装 MySQL 5.7
linux·运维·mysql
霸道流氓气质3 天前
领域驱动设计(DDD)在 Spring Boot 微服务中的实践指南
运维·spring boot·微服务
小宇宙Zz3 天前
Maven依赖冲突
java·服务器·maven
Inhand陈工3 天前
基于台达PLC与映翰通IG502的智慧水产养殖精准投喂与远程运维解决方案
运维·人工智能·物联网·阿里云·信息与通信
酣大智3 天前
ARP代理--工作原理
运维·网络·arp·arp代理
智通3 天前
Node.js事件循环核心机制
node.js