使用 Node 和 Express 创建第一个 API 的分步指南
如今,API 无处不在。如果你是一名 Web 开发者,你可能至少听说过一次。在本指南的最后,你将拥有第一个使用 Node.Js 和 Express.Js 的 API。
当我开始从事 Web 编程时,后端代码和前端代码是在同一个地方编写的。几个月后,我在第一次实习中发现了如何创建 API,这彻底改变了我的编程方式。
在本分步指南中,我们将一起创建您的第一个 API!希望您喜欢书籍,因为本文将围绕这个主题展开。如果您不喜欢,也不用担心!您可以用巧克力、葡萄酒或任何您想要的东西来代替书籍!
先决条件
为了创建您的第一个 API,我们将使用 Node.Js。您需要具备丰富的 JavaScript 知识,以及 Node.Js 和包管理器 NPM 的基本知识。
注意:强烈建议您在开始本教程之前将 Node.Js 版本升级到最新版本。这将有助于您以现代方式(ES6)编写代码,并避免代码中出现潜在问题。
我建议您下载Postman软件。我们将在本教程的后面部分使用它。
图书 API 的任务列表
我认为创建一个简短的 TODO 列表是个好主意。有了它,你会对主要步骤有更好的了解。如果你想在读完这篇文章后进行自我训练,它也会很有用。
待办事项:
- 设置项目
- 初始化你的 API
- 创建您的第一条路线
- 创建获取所有书籍的路线
- 创建添加书籍的路线
- 创建删除书籍的路线
- 创建更新书籍的路线
1. 设置项目
现在 TODO 列表已经定义好了,我们可以开始设置项目了。具体操作如下:在指定的文件夹中打开终端,然后按照以下步骤操作。
# Create your project repository
$ mkdir first-api-with-node-and-express
# Move into your project folder
$ cd first-api-with-node-and-express
# Initialize your Node.Js project with default parameters
$ npm init -y
# Default parameters of `npm init -y` indicate `index.js` as an entry point of the application.
# So we need to create it.
$ touch index.js
一旦您的项目设置了 Node.Js,我们就需要安装 Express.js。
Express.Js 是我们将用来创建 API 的依赖项。它是 JavaScript 中最著名的框架。
# Install Express.js
$ npm install express
现在,如果您打开package.json
文件,您将看到以下几行。
{
"name": "first-api-with-node-and-express",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1"
}
}
您的项目即将准备就绪!
将这些行添加到您的代码中package.json
以使用最新的 JavaScript 功能。这将避免代码中出现潜在问题。
{
/* Don't touch to the lines before */
"dependencies": {
"express": "^4.17.1"
},
/* Add the line below */
"type": "module"
}
2.初始化你的API
现在您的环境已经设置好了,您可以打开index.js
文件并开始编写下面的代码。
// Import Express.js
import express from "express";
// This variable defines the port of your computer where the API will be available
const PORT = 3000;
// This variable instantiate the Express.js library
const app = express();
// The code below starts the API with these parameters:
// 1 - The PORT where your API will be available
// 2 - The callback function (function to call) when your API is ready
app.listen(PORT, () =>
console.log(`The Books API is running on: http://localhost:${PORT}.`)
);
node index.js
现在,你可以在终端中输入代码来运行它。
当出现以下输出时,你的 API 就准备好了!
输出:
$ node index.js
The Books API is running on: http://localhost:3000.
3. 创建你的第一条路线
API 正在使用路由。如果您尝试打开http://localhost:3000,您会注意到出现错误。
Cannot GET /
发生这种情况是因为我们目前没有创建任何路由。
我们的 API 理应拥有一个欢迎路由!因此,我们将创建一个GET路由来显示欢迎消息。
// The code below creates a GET route with these parameters:
// 1 - The route where the code will be executed
// 2 - The function containing the code to execute
app.get("/", (request, response) => {
// The string we want to display on http://localhost:3000
response.send("Welcome on the books API! Take a breath and start using it!");
});
不要忘记重新启动脚本。
输出:
Welcome on the books API! Take a breath and start using it!
4.创建获取所有书籍的路线
现在您已经创建了第一条路线,我们将执行相同的操作,但这次路线将返回书籍列表。
一些提示:
- 路线名称:“/books”
- 变量:字符串列表
- 返回:JSON(JSON 是几乎所有 API 使用的答案格式)
- API 方法:GET(因为我们想要获取所有书籍)
你明白了吗?让我们复制粘贴你在步骤 3中创建的代码。
我们将通过以下方式进行调整:
// Static variable containing your books
let bookList = [
"Make Time: How to Focus on what Matters Every Day",
"The Power Of Habit",
];
// Replace the route name
app.get("/books", (request, response) => {
// The function will return your bookList in a JSON
// Sample: { allBooks: ["Make Time: How to Focus on what Matters Every Day", "The Power Of Habit"]}
return response.json({ allBooks: bookList });
});
您可以连接到https://localhost:3000/books来获取结果!
输出:
{"allBooks":["Make Time: How to Focus on what Matters Every Day","The Power Of
Habit"]}
5.创建添加书籍的路线
我们有一条获取所有书籍的路线,但是如果我们想在其中添加一本书,该怎么办?
在 API 世界中,当我们想要添加日期时,我们使用POST方法。
我们在这里要做的是:
- 向 API 发送书名
- 对待新书
- 发送结果(真或假)
我们可以做的是复制/粘贴/books路线的代码并进行更改。
// Replace the GET method by POST
// Reminder: POST in the API world is used to ADD a data
app.post("/books", (request, response) => {
// TODO: Fill the function
return response.json({ success: false });
});
为了实现该函数,我们需要接收参数。我们将使用body-parser
一个新的 NPM 包来高效地处理它们。
# Install body-parser
$ npm install body-parser
要使用此包,您需要导入它,然后向 Express.js 指示您正在使用它。
在文件的开头,您可以使用以下内容编辑代码:
// Import Express.js
import express from "express";
// Import body-parser (to handle parameters more easily)
import bodyParser from "body-parser";
// This variable defines the port of your computer where the API will be available
const PORT = 3000;
// This variable instantiate the Express.js library
const app = express();
// Indicate to Express.js that you're using an additional plugin to treat parameters
app.use(bodyParser.urlencoded({ extended: true }));
我们现在可以回到您的新路线了!
第一个函数参数request将用于访问请求主体request.body.parameterName
。您可以执行以下操作来获取参数: 。
因为我们知道我们需要一个书名参数,所以我建议...名称!
app.post("/books", (request, response) => {
// We get the parameter 'name' from the body
const bookName = request.body.name;
// We check if the book list includes the new book
// If it is, we return 'false'
if (bookList.includes(bookName)) return response.json({ success: false });
// Otherwise, we add the new book in the list and return 'true'
bookList.push(bookName);
return response.json({ success: true });
});
让我们在浏览器中打开http://localhost:3000/books!哦……你注意到我们获取到了书籍列表吗?
API 与典型的网站不同。您无法通过浏览器访问它。当您使用浏览器访问网站时,会发送GET请求( GET http://localhost:3000/books)。
你还记得在前置要求中我要求你安装Postman吗?
Postman 是最著名的 API 交互工具。你会发现它就像一个浏览器,只不过是针对 API 的!
如何使用 Postman 请求:
第一次打开 Postman 时,您应该会看到这个仪表板。
您可以点击“+”图标来创建您的第一个请求。
然后,您可以在相应的输入框中输入要请求的 URL(http://localhost:3000/books)。这相当于在浏览器的搜索栏中输入 URL。
在 URL 旁边,你可以使用 GET请求。它对应着我们正在执行的请求类型。在本例中,我们要添加一本书,所以这是一个POST请求。点击它,然后选择POST。
一切准备就绪,但我们需要在请求中添加参数。为此,您可以点击“body”选项卡,然后点击“x-www-form-urlencoded”。
注意: “x-www-form-urlencoded”允许您发送简单文本作为参数。
要添加参数,您可以在 URL 搜索栏下方的表格中进行操作。
“Key”是参数名称,“value”是参数值。
注意:在我们的例子中,我们需要一个参数名称。
const bookName = request.body.**name**;
现在您已经准备好了,您可以点击“发送”按钮来查看您的请求结果!
输出:
{
"success": true
}
再次尝试按“发送”按钮。
输出:
{
"success": false
}
输出结果与预期一致,为错误,因为该书已存储在列表中。
注意:您可以通过 Postman 获取所有书籍,以检查您的新书是否包含在其中。具体操作步骤与“如何使用 Postman 请求”相同,但选择GET作为请求模式。
6.创建书籍删除书籍
现在你已经创建了GET和POST方法,流程将始终相同。
在本部分中,我们将在/books上创建一个DELETE方法。我们将传入一个name参数,函数的目标是如果书籍在列表中,则删除它。
app.delete("/books", (request, response) => {
// We get the parameter 'name' from the body
const bookToDelete = request.body.name;
// We create a new array with all elements different from the book to delete
bookList = bookList.filter((book) => book !== bookToDelete);
// We return the new list
return response.json({ allBooks: bookList });
});
注意:我们返回的是新书清单,但您可以自由地回复其他内容。
7. 创建更新书籍的路线
您的 API 中最后一个缺失的功能是更新书名。PUT方法允许您在 API 中更新数据。
例子:
当前:我添加了“Mirocle Morning”,但实际名称是“Miracle Morning”。我应该删除“Mirocle Morning”,然后添加“Miracle Morning”。
我们想要的效果:我添加了“Mirocle Morning”。我将“Mirocle Morning”更新为“Miracle Morning”。
app.put("/books", (request, response) => {
// We get the parameters 'nameToUpdate' and 'updatedName' from the body
const bookToUpdate = request.body.nameToUpdate;
const updatedBook = request.body.updatedName;
// We search if the book to update is in the list
const indexOfBookToUpdate = bookList.findIndex(
(book) => book === bookToUpdate
);
// If it is not a book from the list, we return 'false'
if (indexOfBookToUpdate === -1) return response.json({ success: false });
// Otherwise, we replace the name and return 'true'
bookList[indexOfBookToUpdate] = updatedBook;
return response.json({ success: true });
});
你成功了!你的第一个 API 已经可用,你可以获取所有书籍,并添加、更新或删除书籍!
代码可用
如果您想获取完整代码以便更轻松地探索或运行它,可以访问我的 GitHub。
链接如下:https ://github.com/gael-thomas/First-API-With-Node-And-Express-example
要记住的事情
什么是路由?
路由是完整的 URL 路径。例如“ http://localhost:3000/books ”。
什么是端点?
端点是 URL 路径的结束点。例如,如果你的完整 URL 是" http://localhost:3000/books ",那么你的端点就是"/books"。
API 可以有不同的请求方法,但最常用的是:
- GET:获取数据
- POST:添加数据
- 删除:删除数据
- PUT:更新数据
如果您想要更多类似的内容,您可以在 Twitter 上关注我,我会在那里发布有关 Web 开发、自我提升以及我作为全栈开发人员的历程的推文!
鏂囩珷鏉ユ簮锛�https://dev.to/herewecode/a-step-by-step-guide-to-create-your-first-api-with-node-and-express-462e