返回

Express入门教程:接口开发与MySQL数据库连接(第一部分)

前端

使用 Express.js 构建 REST API 的分步指南

创建 Express 应用程序

首先,使用 npm 安装 Express 包:

npm install express

然后,创建一个新的 Express 应用程序:

const express = require('express');
const app = express();

创建和运行服务器

使用 app.listen() 方法创建并启动服务器:

app.listen(3000, () => {
  console.log('Server is listening on port 3000');
});

这将在端口 3000 上启动服务器。

设置 Express 中间件

中间件是处理 HTTP 请求的函数。使用 app.use() 方法设置它们:

app.use((req, res, next) => {
  console.log('A request was received');
  next();
});

这将创建一个记录所有请求的中间件。

处理 HTTP 请求

使用特定的 HTTP 方法(例如 app.get())处理请求:

app.get('/', (req, res) => {
  res.send('Hello, world!');
});

这将处理发送到根 URL(/)的所有 GET 请求。

路由参数和查询参数

可以使用路由参数和查询参数从请求中获取数据:

app.get('/users/:id', (req, res) => {
  res.send(`User ID: ${req.params.id}`);
});

app.get('/search', (req, res) => {
  res.send(`Search query: ${req.query.q}`);
});

响应数据

可以使用 res.send()res.json() 方法发送响应:

res.send('Plain text response');
res.json({ message: 'JSON response' });

处理错误

使用 app.use() 作为错误处理程序:

app.use((err, req, res, next) => {
  res.status(500).send('An error occurred');
});

常见问题解答

  • 如何设置 Express 会话?
const session = require('express-session');

app.use(session({
  secret: 'your-secret-key',
  resave: false,
  saveUninitialized: true
}));
  • 如何使用 Express 进行身份验证?

可以使用 Passport.js 或 JWT(JSON Web 令牌):

const passport = require('passport');

app.use(passport.initialize());
  • 如何连接到数据库?

可以使用 Sequelize、Mongoose 或 Knex.js 等 ORM(对象关系映射器):

const Sequelize = require('sequelize');

const sequelize = new Sequelize('database', 'username', 'password', {
  host: 'localhost',
  dialect: 'mysql'
});
  • 如何部署 Express 应用程序?

可以使用 Heroku、Vercel 或 AWS Elastic Beanstalk 等平台:

heroku create
git push heroku main
  • 如何优化 Express 应用程序?

使用缓存、缩小和负载平衡:

app.use(express.static('public'));
app.use(express.json());

结论

Express.js 是构建 REST API 的一个强大工具。遵循这些步骤,你可以轻松创建和部署你的应用程序。