Express.js中的REST API

223 阅读4分钟

你好在本教程中,我们将在运行于Express.js服务器的Node.js环境中建立一个REST API。

1.1.简介

RESTful API是指应用程序之间相互通信的标准网络服务接口。这种API符合REST的架构风格和约束。它是可扩展的、无状态的、可缓存的,并且有一个统一的接口。它利用HTTP请求,四个最常见的HTTP方法是POST、PUT、GET和DELETE。另一方面,Express.js是最流行的Node.js网络框架,为开发网络和移动应用提供了一套强大的功能。它提供的功能包括---

  • 设置中间件来响应HTTP请求
  • 定义路由表,根据HTTP方法执行不同的行动
  • 允许动态地渲染HTML页面

1.1 设置Node.js

要在Windows上设置Node.js,你需要从这个链接下载安装程序。点击你的平台的安装程序(也包括NPM包管理器),运行安装程序,开始Node.js设置向导。按照向导的步骤操作,完成后点击 "完成"。如果一切顺利,你可以导航到命令提示符来验证安装是否成功,如图1所示。

express js rest api - nmp installation

图 1: 验证 node 和 npm 的安装

2.Express.js中的REST API

为了设置应用程序,我们需要导航到我们项目所在的路径。对于编程的东西,我正在使用Visual Studio Code作为我的首选IDE。你可以自由选择你喜欢的IDE。

2.1 设置依赖性

导航到项目目录,运行npm init -y ,创建一个package.json 文件。这个文件保存着与项目有关的元数据,用于管理项目的依赖性、脚本、版本等。在该文件中添加以下代码,我们将指定所需的依赖性。

package.json

{
  "name": "expressjs-restapi",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.19.0",
    "express": "^4.17.1"
  },
  "devDependencies": {
    "nodemon": "^2.0.7",
    "underscore": "^1.13.1"
  }
}

要下载依赖项,请导航到包含该文件的目录路径,并使用npm install 命令。如果一切顺利,依赖将被加载到node_modules 文件夹中,你就可以进行下一步的操作了。

2.2 创建控制器文件

src/api 文件夹中创建一个控制器文件。这个文件将暴露出端点,负责处理来自客户端的请求。作为一种改进,你可以加强本教程与数据库的交互,在模型对象的帮助下执行CRUD操作。为了简单起见,我们保持控制器文件的简单性,你可以根据自己的意愿自由修改它。

routes.js

const express = require('express');
const router = express.Router();
const _ = require('underscore');

let employees = [
    {"id":1,"full_name":"Sarine Heatherington","email":"sheatherington0@goo.ne.jp","gender":"Polygender","mobile":"870-915-1187"},
    {"id":2,"full_name":"Anatollo Dudding","email":"adudding1@tinyurl.com","gender":"Polygender","mobile":"229-523-4940"},
    {"id":3,"full_name":"Mordy Flux","email":"mflux2@csmonitor.com","gender":"Male","mobile":"905-446-7491"},
    {"id":4,"full_name":"Larina Mallebone","email":"lmallebone3@smh.com.au","gender":"Male","mobile":"938-933-8220"},
    {"id":5,"full_name":"Neal Doidge","email":"ndoidge4@state.gov","gender":"Male","mobile":"344-976-2688"}
];

// create and save a new employee
// http://localhost:4001/api/create
// note - provide the json request body
/*
{
    "full_name": "Cierra Vega",
    "email": "cierra.vega@automation.com",
    "gender": "female",
    "mobile": "603-367-2819"
}
 */
router.post('/create', (req, res) => {
    // skipping request body validations for brevity

    let empId = employees[employees.length - 1].id + 1;
    employees.push({
        id: empId,
        full_name: req.body.full_name,
        email: req.body.email,
        gender: req.body.gender,
        mobile: req.body.mobile
    });

    res.status(201).json({info: `Entity ${empId} created successfully`});
});

// get all employees
// http://localhost:4001/api/findAll
router.get('/findAll', (req, res) => {
    res.status(200).json({info: employees});
});

// get a single employee
// http://localhost:4001/api/findById?id=1
router.get('/findById', (req, res) => {
    if (_.isEmpty(req.query.id)) {
        res.status(400).json({info: 'Id cannot be null'});
    }

    let data = employees.filter(function (emp) {
        if (emp.id == req.query.id) {
            return true;
        }
    });

    if (_.isEmpty(data)) {
        res.status(404).json({info: 'Entity not found'});
    } else {
        res.status(200).json({info: data});
    }
});

// other HTTP methods like PUT, DELETE are skipped for brevity.
// you can add them on your own.

// routes
module.exports = router;

2.3 创建一个索引文件

创建一个索引文件,作为我们服务器的入口。该文件将包含定义应用程序端点的路由的代码。

index.js

const express = require('express');
const bodyParser = require('body-parser');
const app = express();

// Parse requests of Content-Type - application/json
app.use(bodyParser.json());
// Application routes
app.use('/api', require('./src/api/routes'));

const PORT = process.env.port || 4001;
app.listen(PORT, () => {
    console.log(`Server started on port ${PORT}`);
});

3.运行应用程序

要运行该应用程序,请导航到项目目录,并输入以下命令,如图4所示。如果一切顺利,应用程序将在端口号4001 上成功启动。

express js rest api - starting the app

Fig. 3: 启动应用程序

4.项目演示

当应用程序启动后,打开Postman工具来打应用程序的端点。你可以自由地选择任何你喜欢的工具。

应用程序端点

同样地,你也可以创建其他的端点。本教程就讲到这里,我希望这篇文章能为你提供你想要的东西。学习愉快,别忘了分享

5.总结

在本教程中,我们学到了

  • RESTful API和Express.js的介绍
  • 设置Node.js的步骤
  • 通过Express.js创建RESTful端点的编程实例

你可以从下载部分下载本教程的源代码。

6.下载项目

这是一个在node.js环境下创建RESTful API端点的编程教程。

下载
你可以在这里下载这个例子的完整源代码。 Express.js中的REST API