上一篇教程中,我们学习了 REST 架构、REST 的六大约束、如何理解 HTTP 请求方法及其响应代码,以及 RESTful API 端点的构成。
本教程将为我们的 API 设置一个服务器。您可以使用任何编程语言和服务器软件构建 API,但我们将使用 Node.js(JavaScript 的后端实现)和 Express(一个流行的、极简的 Node 框架)。
我们的首要前提是确保 Node.js 和 npm 在计算机上全局安装。我们可以使用 express-api
测试两者并切换到它。
mkdir express-api && cd express-api
现在我们位于新目录中,我们可以使用安装命令以及每个依赖项来初始化我们的项目,以完成项目的设置。
npm install body-parser express mysql request
这将创建一个 package-lock.json
文件和一个 node_modules
目录,并且我们的 package.json
将更新为如下所示:
{ "name": "express-app", "version": "1.0.0", "description": "", "main": "index.js", "author": "AsyncBanana", "license": "MIT", "dependencies": { "body-parser": "^1.19.2", "express": "^4.17.3", "mysql": "^2.18.1", "node-fetch": "^3.2.0" } }
然后,我们需要添加 "scripts" 对象。"scripts" 对象可以帮助我们运行代码。
{ "name": "express-app", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "start": "node index.js" }, "author": "AsyncBanana", "license": "MIT", "dependencies": { "body-parser": "^1.19.2", "express": "^4.17.3", "mysql": "^2.18.1", "node-fetch": "^3.2.0" }, "type": "module" }
ECMAScript 模块 (或 ESM) 是一个新的规范,用于连接浏览器和 Node 等环境中的脚本。它取代了旧的规范,例如 Node 默认使用的 CommonJS (CJS)。在本教程中,我们将使用所有 ESM。
在开始设置 Express 服务器之前,我们将使用 Node 内置的 http
模块快速设置一个 HTTP 服务器,设置一个端口号(我选择 createServer()
方法)。
// 使用 Node 的 HTTP 模块构建服务器 import { createServer } from "http"; const port = 3001; const server = createServer();
在介绍性 REST 文章中,我们讨论了关于 HTTP 服务器的请求和响应。我们将设置我们的服务器来处理请求,并在服务器端显示请求的 URL,并在响应端向客户端显示“Hello, server!”消息。
server.on("request", (request, response) => { console.log(`URL: ${request.url}`); response.end("Hello, server!"); });
最后,我们将告诉服务器监听哪个端口,并在出现错误时显示错误。
// 启动服务器 server.listen(port, (error) => { if (error) return console.log(`Error: ${error}`); console.log(`Server is listening on port ${port}`); });
现在,我们可以通过运行我们之前创建的 npm 脚本启动服务器。
npm start
您将在终端中看到此响应:
<code>Server is listening on port 3001</code>
要检查服务器是否正在运行,请访问 https://localhost:3001/hello
,您将看到服务器根目录上的 GET 请求(/
接收请求,我们将显示请求的 URL 和“Hello, Server!”消息)。
app.get("/", (request, response) => { console.log(`URL: ${request.url}`); response.send("Hello, Server!"); });
最后,我们将服务器启动在 listen()
方法上的端口。
const server = app.listen(port, (error) => { if (error) return console.log(`Error: ${error}`); console.log(`Server listening on port ${server.address().port}`); });
现在我们可以对 URL 使用 curl -i
,我们将看到它现在由 Express 提供支持,并且有一些额外的标头,例如 POST
和 body-parser
模块。将 import
语句添加到 index.js
文件的顶部。
import bodyParser from "body-parser"; ...
然后我们将告诉我们的 Express 应用程序使用 curl -i
到服务器,您将看到标头现在返回 GET
路由到根目录(require
中不需要 .js
扩展名。现在我们将移动应用程序的路由器,以便我们可以在 index.js
文件中使用它。
// 导出路由器 export default router;
在 index.js
中,替换路由:
routes(app);
您现在应该能够转到 routes.js
中的 users
变量,其中包含 JSON 格式的一些伪造用户数据。
const users = [ { id: 1, name: "Richard Hendricks", email: "richard@piedpiper.com", }, { id: 2, name: "Bertram Gilfoyle", email: "gilfoyle@piedpiper.com", }, ];
我们将添加另一个 /users
,并通过它发送用户数据。
app.get("/users", (request, response) => { response.send(users); });
重新启动服务器后,您现在可以导航到 http://localhost:3002/users
并查看我们显示的所有数据。
注意:如果您在浏览器上没有 JSON 查看器扩展程序,我强烈建议您下载一个,例如 Chrome 的 JSONVue。这将使数据更容易阅读!
访问我们的 GitHub 仓库以查看本文的完整代码,并将其与您自己的代码进行比较。
在本教程中,我们学习了如何在 Node 中设置内置 HTTP 服务器和 Express 服务器,路由请求和 URL,以及使用 get 请求使用 JSON 数据。
在 RESTful API 系列的最后一期中,我们将把我们的 Express 服务器连接到 MySQL,以便在数据库中创建、查看、更新和删除用户,从而完成 API 的功能。
以上是用node.js和express编码您的第一个API:设置服务器的详细内容。更多信息请关注PHP中文网其他相关文章!