使用Node.js和MySQL创建API服务器
本文介绍如何使用Node.js和MySQL创建API服务器的步骤,这也是从前端迈向全栈的一个开始。
步骤 1:设置项目基础
- 首先,确保开发环境中安装了Node.js和MySQL
- 创建一个新目录作为项目文件夹,并进入这个目录。
mkdir my-api-server cd my-api-server
- 在项目目录中,运行
npm init -y
初始化Node.js项目并创建一个package.json
文件,它将跟踪项目的依赖关系。
步骤 2:安装依赖
- 使用npm安装必要的包。最常用的Node.js框架是Express,它能够快速搭建API服务器。同时,需要一个MySQL客户端库来连接和操作数据库。
npm install express mysql2
- (可选)如果想要更方便地自动重启服务器,可以安装nodemon作为开发依赖。
npm install nodemon --save-dev
步骤 3:搭建MySQL数据库
- 在MySQL数据库中,创建一个新的数据库和表格。
CREATE DATABASE mydb; USE mydb; CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50), email VARCHAR(100) );
或者:
// touch prepare.js
const mysql = require('mysql2');
// 创建连接到数据库的连接
const connection = mysql.createConnection({
host: 'localhost',
user: 'root', // 替换为你的数据库用户名
password: '********', // 替换为你的数据库密码
});
// 连接到 MySQL 服务器
connection.connect(err => {
if (err) throw err;
console.log('Connected to the MySQL server.');
// 创建名为 'mydb' 的新数据库
connection.query('CREATE DATABASE IF NOT EXISTS mydb', (err, result) => {
if (err) throw err;
console.log('Database "mydb" created');// 切换到新创建的数据库
connection.query('USE mydb', (err, result) => {
if (err) throw err;
console.log('Using database "mydb"');
// 创建新表 'users'
const createUsersTable = `
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
email VARCHAR(100)
)
`;
connection.query(createUsersTable, (err, result) => {
if (err) throw err;
console.log('Table "users" created');
connection.end(); // 关闭数据库连接
});
});
});
});
// node prepare.js
步骤 4:编写服务器代码
- 创建一个新文件
index.js
,作为主服务器文件。touch index.js
- 在
index.js
中,导入所需的模块并设置Express服务器。
const express = require('express');
const mysql = require('mysql2');
const app = express();
// 解析JSON请求体
app.use(express.json());
// 创建MySQL连接
const connection = mysql.createConnection({
host: 'localhost',
user: 'root', // 替换为你的用户名
password: '********', // 替换为你的密码
database: 'mydb'
});
// 在数据库连接上测试连接
connection.connect(error => {
if (error) throw error;
console.log('Successfully connected to the database.');
});
// 定义一个API端点
app.get('/users', (req, res) => {
connection.query('SELECT * FROM users', (error, results) => {
if (error) throw error;
res.json(results);
});
});
// 启动服务器
const PORT = process.env.PORT || 5555;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
步骤 5:启动服务器
- 命令行中运行
node index.js
来启动服务器。 - (可选)如果使用了nodemon,可以把启动指令添加到
package.json
文件中的scripts
部分。
然后通过npm命令来启动服务器:{ "scripts": { "start": "node index.js", "dev": "nodemon index.js" } }
npm run dev
步骤 6:测试API
- 使用Postman或curl等工具来测试你的API服务器。
curl http://localhost:5555/users
这是最基础的例子,实际使用时可能需要添加更多的API端点、中间件、错误处理以及数据库操作等。记得不要将数据库的敏感信息(比如用户名和密码)直接硬编码在代码中,而应该使用环境变量或配置文件来管理。
English version
How to Create an API Server with Node.js and MySQL
This article outlines the steps to create an API server using Node.js and MySQL, marking the beginning of transitioning from frontend to full-stack development.
Step 1: Set Up the Project Foundation
- Ensure Node.js and MySQL are installed in the development environment.
- Create a new directory for the project folder and navigate into it:
mkdir my-api-server cd my-api-server
- Inside the project directory, run
npm init -y
to initialize a Node.js project and create apackage.json
file to track project dependencies.
Step 2: Install Dependencies
- Install the necessary packages using npm. The most commonly used Node.js framework is Express, which allows for quick API server setup. A MySQL client library is also needed to connect to and interact with the database:
npm install express mysql2
- (Optional) For convenience in automatically restarting the server, install nodemon as a development dependency:
npm install nodemon --save-dev
Step 3: Set Up MySQL Database
- Create a new database and table within the MySQL database:
CREATE DATABASE mydb;
USE mydb;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
email VARCHAR(100)
);
or, you can use javascript:
// touch prepare.js
const mysql = require('mysql2');
// 创建连接到数据库的连接
const connection = mysql.createConnection({
host: 'localhost',
user: 'root', // 替换为你的数据库用户名
password: '********', // 替换为你的数据库密码
});
// 连接到 MySQL 服务器
connection.connect(err => {
if (err) throw err;
console.log('Connected to the MySQL server.');
// 创建名为 'mydb' 的新数据库
connection.query('CREATE DATABASE IF NOT EXISTS mydb', (err, result) => {
if (err) throw err;
console.log('Database "mydb" created');// 切换到新创建的数据库
connection.query('USE mydb', (err, result) => {
if (err) throw err;
console.log('Using database "mydb"');
// 创建新表 'users'
const createUsersTable = `
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
email VARCHAR(100)
)
`;
connection.query(createUsersTable, (err, result) => {
if (err) throw err;
console.log('Table "users" created');
connection.end(); // 关闭数据库连接
});
});
});
});
// node prepare.js
Step 4: Write Server Code
- Create a new file
index.js
as the main server file:touch index.js
- In
index.js
, import the required modules and set up the Express server:
const express = require('express');
const mysql = require('mysql2');
const app = express();
// 解析JSON请求体
app.use(express.json());
// 创建MySQL连接
const connection = mysql.createConnection({
host: 'localhost',
user: 'root', // 替换为你的用户名
password: '********', // 替换为你的密码
database: 'mydb'
});
// 在数据库连接上测试连接
connection.connect(error => {
if (error) throw error;
console.log('Successfully connected to the database.');
});
// 定义一个API端点
app.get('/users', (req, res) => {
connection.query('SELECT * FROM users', (error, results) => {
if (error) throw error;
res.json(results);
});
});
// 启动服务器
const PORT = process.env.PORT || 5555;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Step 5: Start the Server
- Run
node index.js
in the command line to start the server. - (Optional) If nodemon was installed, add the start command to the
scripts
section of thepackage.json
file:
Then use the npm command to start the server:{ "scripts": { "start": "node index.js", "dev": "nodemon index.js" } }
npm run dev
Step 6: Test the API
- Use tools like Postman or curl to test the API server:
curl http://localhost:5555/users
This is the most basic example, and real-world usage may require adding more API endpoints, middleware, error handling, and database operations. Remember not to hardcode sensitive database information (such as usernames and passwords) directly in the code, but rather manage it using environment variables or configuration files.
转载自:https://juejin.cn/post/7324193090557345842