Node.js 第二课:用核心模块构建你的第一个服务器

创建并运行一个真正的Node.js服务器,理解HTTP模块,学会处理请求与响应。

实战项目:简易天气查询API

1. 创建项目结构

bash 复制代码
mkdir server-demo
cd server-demo
npm init -y
npm install nodemon --save-dev

修改 package.json

json 复制代码
{
  "scripts": {
    "dev": "nodemon server.js"
  }
}

2. 核心模块讲解:http

创建 server.js

javascript 复制代码
// 1. 导入内置的http模块
const http = require('http');

// 2. 创建服务器实例
const server = http.createServer((req, res) => {
  // req: 请求对象,包含客户端的信息
  // res: 响应对象,用于向客户端返回数据
  
  console.log(`收到 ${req.method} 请求,路径: ${req.url}`);
  
  // 设置响应头
  res.writeHead(200, { 
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin': '*'
  });
  
  // 根据请求路径返回不同响应
  if (req.url === '/weather/beijing') {
    res.end(JSON.stringify({
      city: "北京",
      temperature: "22°C",
      condition: "晴天"
    }));
  } else if (req.url === '/weather/shanghai') {
    res.end(JSON.stringify({
      city: "上海",
      temperature: "25°C",
      condition: "多云"
    }));
  } else {
    res.end(JSON.stringify({
      message: "欢迎使用天气API",
      endpoints: ["/weather/beijing", "/weather/shanghai"]
    }));
  }
});

// 3. 监听端口
const PORT = 3000;
server.listen(PORT, () => {
  console.log(`🚀 服务器运行在: http://localhost:${PORT}`);
  console.log(`📡 试试访问: http://localhost:${PORT}/weather/beijing`);
});

3. 运行并测试

bash 复制代码
npm run dev

用三种方式测试:

  1. 浏览器访问 :打开 http://localhost:3000

2 命令行curl

bash 复制代码
curl http://localhost:3000/weather/shanghai
  1. 创建测试文件 test.js
javascript 复制代码
const http = require('http');

const options = {
  hostname: 'localhost',
  port: 3000,
  path: '/weather/beijing',
  method: 'GET'
};

const req = http.request(options, (res) => {
  let data = '';
  
  res.on('data', chunk => {
    data += chunk;
  });
  
  res.on('end', () => {
    console.log('天气数据:', JSON.parse(data));
  });
});

req.end();

知识点总结

✅ 掌握 http.createServer()创建服务器

✅ 理解 reqres对象

✅ 学会设置响应头和状态码

✅ 能根据不同URL返回不同内容

✅ 知道如何用 nodemon热重载

相关推荐
花大师22 分钟前
基于深度学习的鼠标轨迹真实性检测系统
后端
珑墨23 分钟前
前端 AI 开发通用skill
前端
kyriewen24 分钟前
一个人+Cursor,7天上线付费小程序:第1天我就想放弃了
前端·微信小程序·cursor
大家的林语冰29 分钟前
Angular 王者归来,第 22 个主版本亮相,一大波前沿技术再度引领潮流!
前端·javascript·前端框架
小江的记录本41 分钟前
【Spring全家桶】Spring Cloud 2023.0.x:微服务核心理论、CAP/BASE定理(附《思维导图》+《面试高频考点清单》)
java·spring boot·后端·spring·spring cloud·微服务·面试
老毛肚43 分钟前
jeecgboot TS + Vue 模板化 03
前端·javascript·vue.js
下北沢美食家1 小时前
SSE 入门
前端
云计算磊哥@1 小时前
运维开发宝典023-WEB网站服务
运维·前端·运维开发
我登哥MVP1 小时前
Spring Boot 从“会用”到“精通”:Model-Map原理
java·spring boot·后端·spring·servlet·maven·mybatis