Node.js 后端开发之 Express 处理 API 请求

Hello World

npm init -y  # 新建项目
npm install express  # 安装 Express

app.js:

const express = require('express');
const app = express();
const port = 3000;

// 定义一个简单的路由
app.get('/', (req, res) => {
  res.send('Hello, Express!');
});

// 启动服务器
app.listen(port, () => {
  console.log(`Server is running at http://localhost:${port}`);
});

启动服务器:

node app.js

路由

// GET 路由
app.get('/about', (req, res) => {
  res.send('About Page');
});

// POST 路由
app.post('/contact', (req, res) => {
  res.send('Contact Page');
});

// 链式挂载
app.route(path).get(handler).post(handler);

获取参数

  • 路由参数:

    // :word 是参数
    app.get("/:word/echo", (req, res) => {
      const { word } = req.params;  // 取得 word 参数值
      res.json({echo: word});
    });
    

    访问 http://localhost:3000/anything/echo 会得到 {echo: anything}

    从客户端获取输入的路由参数 | freeCodeCamp.org

  • 查询字符串:

    app.get("/name", (req, res) => {
        const { first, last } = req.query;  // 从查询字符串中提取参数
        res.json({name: `${first} ${last}`});
    });
    

    访问 http://localhost:3000/?first=John&last=Connor 会得到 {name: John Connor}

  • 从 POST 请求中获取数据:

    const express = require("express")
    app.use(express.json());  // 处理 POST 请求体的 JSON 数据。
    app.use(express.urlencoded({extended: false}));  // 处理 POST 请求体的 URL 编码数据
    
    app.get("/name", (req, res) => {
        const { first, last } = req.body;
        res.json({name : `${first} ${last}`});
    });
    

    使用 Axios 发送测试数据:

    const axios = require('axios');
    const data = { first: "John", last: "Connor" };
    axios.post('http://localhost:3000/name', data)
      .then(response => {  // 正常响应
        console.log('Response:', response.data);
      })
      .catch(error => {  // 错误处理
        console.error('Error:', error.response.data);
      });
    

    从 POST 请求中获取数据 | freeCodeCamp.org

中间件

// 使用中间件来记录每个请求的时间
app.use((req, res, next) => {
  console.log('Time:', Date.now());
  next();
});

处理静态文件

app.use(express.static('public'));

参见:

posted @ 2024-12-17 15:09  Undefined443  阅读(32)  评论(0)    收藏  举报