面向初学者的使用 Node.js 构建首个 API 指南

发布: (2025年12月2日 GMT+8 17:43)
3 min read
原文: Dev.to

Source: Dev.to

介绍

如果你是后端开发新手,构建 API 可能会让人感到望而生畏。
好消息 — 使用 Node.js 和 Express,你只需几分钟就能创建一个功能完整的 API。

什么是 API?

API(应用程序编程接口) 允许不同的应用程序相互通信。

示例

  • 前端:“给我所有用户。”
  • 后端 API:“给你!”

项目设置

mkdir my-first-api
cd my-first-api
npm init -y
npm install express

创建服务器

创建一个名为 server.js 的文件并添加以下代码:

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

app.use(express.json());

// Home route
app.get('/', (req, res) => {
  res.send({ message: 'Welcome to your first Node.js API!' });
});

// Sample GET route
app.get('/api/users', (req, res) => {
  res.send([
    { id: 1, name: 'John' },
    { id: 2, name: 'Sarah' }
  ]);
});

// In‑memory users array
let users = [
  { id: 1, name: 'John' },
  { id: 2, name: 'Sarah' }
];

// POST route to add a user
app.post('/api/users', (req, res) => {
  const newUser = {
    id: users.length + 1,
    name: req.body.name
  };

  users.push(newUser);
  res.status(201).send(newUser);
});

// Start server
const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});

运行服务器:

node server.js

你应该会看到:

Server running on http://localhost:3000

运行 API

打开浏览器或使用 curlPostman 等工具与端点交互。

  • 首页:http://localhost:3000
  • 获取用户:http://localhost:3000/api/users

使用 curl

curl http://localhost:3000/api/users

使用 Postman(POST)

{
  "name": "Emily"
}

将请求发送到 http://localhost:3000/api/users 以添加新用户。

后续步骤

  • 路由最佳实践 – 将路由组织到独立模块中。
  • 环境变量 – 使用 dotenv 存储配置(例如端口、数据库凭证)。
  • 数据库集成 – 连接 MongoDB、PostgreSQL 等数据库,取代内存数组。
  • 身份验证 – 实现 JWT 或基于会话的认证,以保护路由。
  • 部署 – 将项目部署到 Heroku、Vercel、Render 等平台。

你已经有了一个很好的开端 — 继续前进吧! 🚀

Back to Blog

相关文章

阅读更多 »

使用 API 将问题分配给 Copilot

GraphQL 支持 您可以使用以下 mutation 将问题分配给 Copilot:- updateIssue https://docs.github.com/graphql/reference/mutationsupdateissue - c...

了解 API 及其结构

什么是 API?API 代表 Application Programming Interface(应用程序编程接口)。基本上,API 是一种……