search
HomeCMS TutorialWordPressWrite your first API using Node.js and Express: Connect to the database

Write your first API using Node.js and Express: Connect to the database

Build a REST API using Node.js and Express: Connect to the database

In the first tutorial, "Understanding RESTful APIs," we learned what the REST architecture is, what the HTTP request methods and responses are, and how to understand RESTful API endpoints. In the second tutorial, "How to Set Up an Express API Server", we learned how to build a server using Node's built-in http module and the Express framework, and how to route the application we created to different URL endpoints .

Currently, we use static data to display user information in the form of a JSON source when the API endpoint is hit by a GET request. In this tutorial, we will set up a MySQL database to store all the data, connect to the database from the Node.js application, and allow the API to use GET, POST, PUT , and DELETE methods create a complete API.

Install

So far we haven't used a database to store or manipulate any data, so we'll set one up. This tutorial will use MySQL, if you already have MySQL installed on your computer, you can continue to the next step.

If you don't have MySQL installed, you can download MAMP for macOS and Windows, which provides a free local server environment and database. After the download is complete, open the program and click Start Server to start MySQL.

In addition to setting up MySQL itself, we also need GUI software to view the database and tables. For Mac, download SequelPro or for Windows, SQLyog. After downloading and running MySQL, you can use SequelPro or SQLyog to connect to localhost on port 3306 using username root and password root .

Once everything is set up here, we can move on to setting up the database for the API.

Set up database

In the database viewing software, add a new database and name it api. Make sure MySQL is running or you will not be able to connect to localhost.

After creating the api database, move into it and run the following query to create the new table.

CREATE TABLE `users` (
  `id`       int(11)     unsigned NOT NULL AUTO_INCREMENT,
  `name`     varchar(30) DEFAULT '',
  `email`    varchar(50) DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

This SQL query will create the structure of the users table. Each user will have an auto-incrementing ID, name, and email address.

We can also populate the database with the same data currently displayed via a static JSON array by running an INSERT query.

INSERT INTO users (name, email) 
     VALUES ('Richard Hendricks', 'richard@piedpiper.com'), 
            ('Bertram Gilfoyle',  'gilfoyle@piedpiper.com');
The

id field does not require input as it is auto-incremented. At this point, we have the structure of the table and some sample data to work with.

Connect to MySQL

Back to our application, we have to connect to MySQL from Node.js to start processing data. Previously, we installed the mysql npm module and now we want to use it.

Create a new directory called data and create a config.js file.

We first need the mysql module in data/config.js.

const mysql = require('mysql');

Let's create a config object that contains the host, user, password and database. This should reference the api database we made and use the default localhost settings.

// Set database connection credentials
const config = {
    host: 'localhost',
    user: 'root',
    password: 'root',
    database: 'api',
};

To improve efficiency, we will create a MySQL pool that allows us to use multiple connections at once without having to manually open and close multiple connections.

// Create a MySQL pool
const pool = mysql.createPool(config);

Finally, we will export the MySQL pool so that the application can use it.

// Export the pool
module.exports = pool;

You can view the complete database configuration files in our GitHub repository.

Now that we are connecting to MySQL and the setup is complete, we can continue to interact with the database through the API.

Get API data from MySQL

Currently, our routes.js file is manually creating a JSON array of users as shown below.

const users = [{ ...

Since we are no longer using static data, we can delete the entire array and replace it with a link to the MySQL pool.

// Load the MySQL pool connection
const pool = require('../data/config');

Previously, a GET of the /users path sent static users data. Our updated code will query the database for this data instead. We will use SQL query SELECT from the users table as shown below.

SELECT * FROM users

This is what our new /users looks like to get the route, using the pool.query() method.

// Display all users
app.get('/users', (request, response) => {
    pool.query('SELECT * FROM users', (error, result) => {
        if (error) throw error;

        response.send(result);
    });
});

Here we run the SELECT query and send the results to the client as JSON via the /users endpoint. If you restart the server and navigate to the /users page, you will see the same data as before, but now it is dynamic.

使用 URL 参数

到目前为止,我们的端点都是静态路径 - / root 或 /users - 但是当我们只想查看有关特定用户的数据时该怎么办?我们需要使用可变端点。

对于我们的用户,我们可能希望根据每个用户的唯一 ID 检索有关每个用户的信息。为此,我们将使用冒号 (:) 来表示它是一个路由参数。

// Display a single user by ID
app.get('/users/:id', (request, response) => {
        ...
    });
});

我们可以使用 request.params 属性检索此路径的参数。由于我们的名称为 id,因此我们将这样引用它。

const id = request.params.id;

现在,我们将在 SELECT 语句中添加 WHERE 子句,以仅获取具有指定 id 的结果。

我们将使用 ? 作为占位符以避免 SQL 注入,并将 id 作为参数传递,而不是构建一个连接字符串,这会降低安全性。

pool.query('SELECT * FROM users WHERE id = ?', id, (error, result) => {
    if (error) throw error;

    response.send(result);
});

我们个人用户资源的完整代码现在如下所示:

// Display a single user by ID
app.get('/users/:id', (request, response) => {
    const id = request.params.id;

    pool.query('SELECT * FROM users WHERE id = ?', id, (error, result) => {
        if (error) throw error;

        response.send(result);
    });
});

现在您可以重新启动服务器并导航到 https://localhost/users/2 以仅查看 Gilfoyle 的信息。如果出现 Cannot GET /users/2 之类的错误,则说明您需要重新启动服务器。

访问此 URL 应返回一个结果。

[{
    id: 2,
    name: "Bertram Gilfoyle",
    email: "gilfoyle@piedpiper.com"
}]

如果您看到的是这样的内容,那么恭喜您:您已成功设置动态路由参数!

发送 POST 请求

到目前为止,我们所做的一切都使用了 GET 请求。这些请求是安全的,这意味着它们不会改变服务器的状态。我们只是查看 JSON 数据。

现在我们将开始通过使用 POST 请求添加新数据来使 API 真正动态化。

我之前在理解 REST 文章中提到,我们不会在 URL 中使用 adddelete 等动词来执行操作。为了向数据库添加新用户,我们将 POST 到我们查看它们的同一 URL,但只需为其设置一个单独的路由。

// Add a new user
app.post('/users', (request, response) => {
    ...
});

请注意,我们现在使用 app.post() 而不是 app.get()

由于我们是创建而不是读取,因此我们将在此处使用 INSERT 查询,就像我们在数据库初始化时所做的那样。我们将整个 request.body 发送到 SQL 查询。

pool.query('INSERT INTO users SET ?', request.body, (error, result) => {
    if (error) throw error;

我们还将指定响应的状态为 201,它代表 Created。为了获取最后插入的项目的 id,我们将使用 insertId 属性。

response.status(201).send(`User added with ID: ${result.insertId}`);

我们的整个 POST 接收代码将如下所示。

// Add a new user
app.post('/users', (request, response) => {
    pool.query('INSERT INTO users SET ?', request.body, (error, result) => {
        if (error) throw error;

        response.status(201).send(`User added with ID: ${result.insertId}`);
    });
});

现在我们可以通过发送一个 POST 请求了。大多数情况下,当您发送 POST 请求时,您是通过 Web 表单执行的。我们将在本文末尾学习如何进行设置,但发送测试 POST 的最快、最简单的方法是使用 cURL,使用 -d (--data) 标志。

我们将运行 curl -d,后跟包含所有键/值对和请求端点的查询字符串。

curl -d "name=Dinesh Chugtai&email=dinesh@piedpiper.com" http://localhost:3002/users

发送此请求后,您应该会从服务器收到响应。

User added with ID: 3

如果您导航到 http://localhost/users,您将看到添加到列表中的最新条目。

发送 PUT 请求

POST 对于添加新用户很有用,但我们希望使用 PUT 来修改现有用户。 PUT 是幂等的,这意味着您可以多次发送相同的请求,并且只会执行一个操作。这与 POST 不同,因为如果我们多次发送新用户请求,它会不断创建新用户。

对于我们的 API,我们将设置 PUT 以便能够处理编辑单个用户,因此这次我们将使用 :id 路由参数。

让我们创建一个 UPDATE 查询,并确保它仅适用于带有 WHERE 子句的请求 ID。我们使用两个 ? 占位符,我们传递的值将按顺序排列。

// Update an existing user
app.put('/users/:id', (request, response) => {
    const id = request.params.id;

    pool.query('UPDATE users SET ? WHERE id = ?', [request.body, id], (error, result) => {
        if (error) throw error;

        response.send('User updated successfully.');
    });
});

在我们的测试中,我们将编辑用户 2 并将电子邮件地址从 gilfoyle@piedpiper.com 更新为 bertram@piedpiper.com。我们可以再次使用 cURL,并使用 [-X (--request)] 标志来明确指定我们要通过其发送 PUT 请求。

curl -X PUT -d "name=Bertram Gilfoyle" -d "email=bertram@piedpiper.com" http://localhost:3002/users/2

请确保在发送请求之前重新启动服务器,否则您将收到 Cannot PUT /users/2 错误。

你应该看到这个:

User updated successfully.

现在应该更新 ID 为 2 的用户数据。

发送删除请求

我们完成 API 的 CRUD 功能的最后一个任务是选择从数据库中删除用户。此请求将使用 DELETE SQL 查询和 WHERE,并且它将删除由路由参数指定的单个用户。

// Delete a user
app.delete('/users/:id', (request, response) => {
    const id = request.params.id;

    pool.query('DELETE FROM users WHERE id = ?', id, (error, result) => {
        if (error) throw error;

        response.send('User deleted.');
    });
});

我们可以再次使用 -X 和 cURL 来发送删除。让我们删除我们创建的最新用户。

curl -X DELETE http://localhost:3002/users/3

您将看到成功消息。

User deleted.

导航到 http://localhost:3002,您会看到现在只有两个用户。

恭喜!至此,API就完成了。访问 GitHub 存储库以查看 routes.js 的完整代码。

通过request模块发送请求

在本文的开头,我们安装了四个依赖项,其中之一是 request 模块。您可以创建一个包含所有数据的新文件并将其发送,而不是使用 cURL 请求。我将创建一个名为 post.js 的文件,该文件将通过 POST 创建一个新用户。

const request = require('request');

const json = {
    "name": "Dinesh Chugtai",
    "email": "dinesh@piedpiper.com",
};

request.post({
    url: 'http://localhost:3002/users',
    body: json,
    json: true,
}, function (error, response, body) {
    console.log(body);
});

我们可以在服务器运行时在新的终端窗口中使用 node post.js 来调用它,它与使用 cURL 具有相同的效果。如果 cURL 出现问题,request 模块很有用,因为我们可以查看错误、响应和正文。

通过 Web 表单发送请求

通常,POST 和其他改变服务器状态的 HTTP 方法是使用 HTML 表单发送的。在这个非常简单的示例中,我们可以在任何地方创建一个 index.html 文件,并为姓名和电子邮件地址创建一个字段。表单的操作将指向资源,在本例中为 http//localhost:3002/users,我们将方法指定为 post

创建index.html并向其中添加以下代码:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Node.js Express REST API</title>
</head>

<body>
    <form action="http://localhost:3002/users" method="post">
        <label for="name">Name</label>
        <input type="text" name="name">
        <label for="email">Email</label>
        <input type="email" name="email">
        <input type="submit">
    </form>
</body>

</html>

在浏览器中打开此静态 HTML 文件,填写该文件,然后在服务器在终端中运行时发送它。您应该会看到 添加了 ID 为 4 的用户的响应,并且您应该能够查看新的用户列表。

结论

在本教程中,我们学习了如何将 Express 服务器连接到 MySQL 数据库,并设置与路径和动态路由的 GETPOSTPUTDELETE 方法相对应的路由参数。我们还学习了如何使用 cURL、Node.js request 模块和 HTML 表单向 API 服务器发送 HTTP 请求。

此时,您应该非常了解 RESTful API 的工作原理,并且您现在可以使用 Express 和 MySQL 在 Node.js 中创建自己的成熟 API!

The above is the detailed content of Write your first API using Node.js and Express: Connect to the database. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does WordPress's plugin ecosystem enhance its CMS capabilities?How does WordPress's plugin ecosystem enhance its CMS capabilities?May 14, 2025 am 12:20 AM

WordPresspluginssignificantlyenhanceitsCMScapabilitiesbyofferingcustomizationandfunctionality.1)Over50,000pluginsallowuserstotailortheirsiteforSEO,e-commerce,andsecurity.2)Pluginscanextendcorefeatures,likeaddingcustomposttypes.3)However,theycancausec

Is WordPress suitable for e-commerce?Is WordPress suitable for e-commerce?May 13, 2025 am 12:05 AM

Yes, WordPress is very suitable for e-commerce. 1) With the WooCommerce plugin, WordPress can quickly become a fully functional online store. 2) Pay attention to performance optimization and security, and regular updates and use of caches and security plug-ins are the key. 3) WordPress provides a wealth of customization options to improve user experience and significantly optimize SEO.

How to add your WordPress site in Yandex Webmaster ToolsHow to add your WordPress site in Yandex Webmaster ToolsMay 12, 2025 pm 09:06 PM

Do you want to connect your website to Yandex Webmaster Tools? Webmaster tools such as Google Search Console, Bing and Yandex can help you optimize your website, monitor traffic, manage robots.txt, check for website errors, and more. In this article, we will share how to add your WordPress website to the Yandex Webmaster Tool to monitor your search engine traffic. What is Yandex? Yandex is a popular search engine based in Russia, similar to Google and Bing. You can excel in Yandex

How to fix HTTP image upload errors in WordPress (simple)How to fix HTTP image upload errors in WordPress (simple)May 12, 2025 pm 09:03 PM

Do you need to fix HTTP image upload errors in WordPress? This error can be particularly frustrating when you create content in WordPress. This usually happens when you upload images or other files to your CMS using the built-in WordPress media library. In this article, we will show you how to easily fix HTTP image upload errors in WordPress. What is the reason for HTTP errors during WordPress media uploading? When you try to upload files to Wo using WordPress media uploader

How to fix the issue where adding media buttons don't work in WordPressHow to fix the issue where adding media buttons don't work in WordPressMay 12, 2025 pm 09:00 PM

Recently, one of our readers reported that the Add Media button on their WordPress site suddenly stopped working. This classic editor problem does not show any errors or warnings, which makes the user unaware why their "Add Media" button does not work. In this article, we will show you how to easily fix the Add Media button in WordPress that doesn't work. What causes WordPress "Add Media" button to stop working? If you are still using the old classic WordPress editor, the Add Media button allows you to insert images, videos, and more into your blog post.

How to set, get and delete WordPress cookies (like a professional)How to set, get and delete WordPress cookies (like a professional)May 12, 2025 pm 08:57 PM

Do you want to know how to use cookies on your WordPress website? Cookies are useful tools for storing temporary information in users’ browsers. You can use this information to enhance the user experience through personalization and behavioral targeting. In this ultimate guide, we will show you how to set, get, and delete WordPresscookies like a professional. Note: This is an advanced tutorial. It requires you to be proficient in HTML, CSS, WordPress websites and PHP. What are cookies? Cookies are created and stored when users visit websites.

How to Fix WordPress 429 Too Many Request ErrorsHow to Fix WordPress 429 Too Many Request ErrorsMay 12, 2025 pm 08:54 PM

Do you see the "429 too many requests" error on your WordPress website? This error message means that the user is sending too many HTTP requests to the server of your website. This error can be very frustrating because it is difficult to find out what causes the error. In this article, we will show you how to easily fix the "WordPress429TooManyRequests" error. What causes too many requests for WordPress429? The most common cause of the "429TooManyRequests" error is that the user, bot, or script attempts to go to the website

How scalable is WordPress as a CMS for large websites?How scalable is WordPress as a CMS for large websites?May 12, 2025 am 12:08 AM

WordPresscanhandlelargewebsiteswithcarefulplanningandoptimization.1)Usecachingtoreduceserverload.2)Optimizeyourdatabaseregularly.3)ImplementaCDNtodistributecontent.4)Vetpluginsandthemestoavoidconflicts.5)ConsidermanagedWordPresshostingforenhancedperf

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)