Express.js 是一个灵活的 Node.js Web 应用框架,它可以帮助你快速搭建 Web 应用。本指南将带你了解 Express.js 的基本使用方法。
快速开始
- 安装 Node.js
- 创建一个新目录,并初始化 npm
mkdir myapp cd myapp npm init -y
- 安装 Express
npm install express
- 创建一个简单的 Express 应用
const express = require('express'); const app = express(); app.get('/', (req, res) => { res.send('Hello, World!'); }); app.listen(3000, () => { console.log('Server is running on http://localhost:3000'); });
路由和中间件
Express.js 使用路由和中间件来处理请求。
路由
路由定义了 URL 和对应的处理函数。以下是一个简单的路由示例:
app.get('/about', (req, res) => {
res.send('About Page');
});
中间件
中间件是一个函数,它可以在请求处理链中插入额外的逻辑。以下是一个简单的中间件示例:
app.use((req, res, next) => {
console.log('Request received');
next();
});
app.get('/', (req, res) => {
res.send('Hello, World!');
});
模板引擎
Express.js 支持多种模板引擎,如 EJS、Pug、Handlebars 等。以下是一个使用 EJS 的示例:
- 安装 EJS
npm install ejs
- 设置模板引擎
app.set('view engine', 'ejs');
- 创建视图文件
在
views
目录下创建一个名为index.ejs
的文件,并添加以下内容:<!DOCTYPE html> <html> <head> <title><%= title %></title> </head> <body> <h1><%= message %></h1> </body> </html>
- 修改路由
app.get('/', (req, res) => { res.render('index', { title: 'Home', message: 'Welcome to my site!' }); });
图片示例
狗狗品种
下面是一些狗狗品种的图片:
- Golden Retriever
- Poodle
- Bulldog