Node.js 路由 - 初识 Express 中的路由

目录

[Node.js 路由 - 初识 Express 中的路由](#Node.js 路由 - 初识 Express 中的路由)

[1. 什么是路由?](#1. 什么是路由?)

[2. 安装 Express](#2. 安装 Express)

[3. 创建 server.js](#3. 创建 server.js)

[4. 运行服务器](#4. 运行服务器)

[5. 测试路由](#5. 测试路由)

[5.1 访问主页](#5.1 访问主页)

[5.2 访问用户路由](#5.2 访问用户路由)

[5.3 发送 POST 请求](#5.3 发送 POST 请求)

[6. 结语](#6. 结语)


1. 什么是路由?

路由(Routing)是指根据不同的 URL 地址,服务器返回不同的内容 。在 Express 中,我们可以使用 app.get()app.post() 等方法定义路由。


2. 安装 Express

bash 复制代码
mkdir express-routing && cd express-routing  # 创建项目目录
npm init -y  # 初始化项目
npm install express  # 安装 Express

3. 创建 server.js

文件名:server.js(JavaScript 代码)

javascript 复制代码
// server.js
const express = require('express'); // 引入 Express
const app = express(); // 创建应用
const port = 3000; // 服务器端口

// 主页路由
app.get('/', (req, res) => {
    res.send('欢迎来到 Express 主页!');
});

// 用户路由(GET 请求)
app.get('/user/:name', (req, res) => {
    const name = req.params.name; // 获取 URL 参数
    res.send(`你好,${name}!`);
});

// 提交数据路由(POST 请求)
app.use(express.json()); // 解析 JSON 请求体
app.post('/submit', (req, res) => {
    const { username, age } = req.body; // 获取请求体数据
    res.json({ message: '数据提交成功', user: { username, age } });
});

// 启动服务器
app.listen(port, () => {
    console.log(`服务器运行在 http://localhost:${port}`);
});

4. 运行服务器

执行命令:

bash 复制代码
node server.js

5. 测试路由

5.1 访问主页

浏览器打开 http://localhost:3000/,页面显示:

javascript 复制代码
欢迎来到 Express 主页!
5.2 访问用户路由

浏览器访问 http://localhost:3000/user/Tom,页面显示:

javascript 复制代码
你好,Tom!
5.3 发送 POST 请求

使用 Postman 或 curl 发送请求:

javascript 复制代码
curl -X POST http://localhost:3000/submit -H "Content-Type: application/json" -d '{"username": "Alice", "age": 25}'

服务器返回 JSON 响应:

javascript 复制代码
{
    "message": "数据提交成功",
    "user": {
        "username": "Alice",
        "age": 25
    }
}

6. 结语

本文介绍了 Express 路由 的基本用法,包括 GET 和 POST 请求,以及如何获取 URL 参数和请求体数据。希望这篇教程能帮助你快速上手 Express 路由!🚀

相关推荐
计算机魔术师3 分钟前
Google DeepMind 将 AI 科学家 Co-Scientist 扩展为实验室集成研究伙伴
前端
2601_9657984712 分钟前
BrandBoost WordPress Theme Review: Fast Agency Web Architecture
前端
律宏阔15 分钟前
Electron 集成 Drizzle + SQLite 踩坑笔记
前端
律宏阔18 分钟前
Electron preload.ts 类型无法自动推导的解决方案
前端
名字还没想好☜29 分钟前
kubectl 排障实战:jsonpath 精准取值、custom-columns、events 排序与 top 速查
运维·前端·chrome·docker·kubernetes
李昊哲小课36 分钟前
Spring Boot 4 旅游主题实战教程 阶段二:Web 开发基础
前端·spring boot·旅游
ITmaster07311 小时前
从零到一!前端搭建本地轻量化 RAG 问答系统
前端
夏炳辉.2 小时前
Flex布局中 flex: 1 的完整解析与实战指南
前端·css·css3
CIO_Alliance2 小时前
AI提示系列(2)| Few-shot与ReAct有何不同? 大模型工具调用的底层逻辑详解
前端·人工智能·深度学习·神经网络·react.js·前端框架·ai+ipaas
cindershade2 小时前
别只收三个数字:前端 RUM 如何建立可解释的体验数据链
前端