Node.js 监听 GET 和 POST 请求并处理参数

发布于:2025-03-28 ⋅ 阅读:(31) ⋅ 点赞:(0)

目录

 

1. 安装 Node.js 和 Express

2. 创建服务器并监听 GET 和 POST 请求

3. 运行服务器

4. 结语


 

1. 安装 Node.js 和 Express

在开始之前,请确保你已经安装了 Node.js,然后使用 npm 安装 Express

mkdir node-server && cd node-server  # 创建项目目录
npm init -y  # 初始化项目
npm install express  # 安装 Express

2. 创建服务器并监听 GET 和 POST 请求

新建 server.js 文件,写入以下代码:

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

// 解析 JSON 和 URL 编码数据
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 监听 GET 请求,获取查询参数
app.get('/get-user', (req, res) => {
    const name = req.query.name; // 获取 URL 查询参数 ?name=xxx
    res.send(`GET 请求收到,用户:${name}`);
});

// 监听 POST 请求,获取请求体数据
app.post('/post-user', (req, res) => {
    const { name, age } = req.body; // 获取 JSON 请求体参数
    res.json({ message: 'POST 请求收到', user: { name, age } });
});

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

3. 运行服务器

在终端执行:

node server.js

服务器启动后,访问 http://localhost:3000/get-user?name=Tom,页面会返回:

GET 请求收到,用户:Tom

然后使用 Postman 或 curl 发送 POST 请求:

curl -X POST http://localhost:3000/post-user -H "Content-Type: application/json" -d '{"name": "Alice", "age": 25}'

服务器返回 JSON 响应:

{
    "message": "POST 请求收到",
    "user": {
        "name": "Alice",
        "age": 25
    }
}

4. 结语

这篇文章介绍了如何使用 Node.js + Express 监听 GET 和 POST 请求,并解析 URL 查询参数和 JSON 请求体数据。希望这篇教程能帮助你快速上手!🚀