Skip to Content
Node与Express开发(第2版)
book

Node与Express开发(第2版)

by Ethan Brown
June 2021
Intermediate to advanced
290 pages
9h 21m
Chinese
Posts & Telecom Press
Content preview from Node与Express开发(第2版)
Express
的方式
|
25
// 定制500页
app.use((err, req, res, next) => {
console.error(err.message)
res.status(500)
res.render('500')
})
注意我们不再需要指定内容类型或状态码:视图引擎会默认返回
text/html
内容类型和
200
状态码。在
404
页和
500
页的兜底处理函数中,必须明确设置状态码。
如果你启动服务器,访问主页或“关于”页,会看到视图得到了渲染。如果你查看页面源
代码,会看到来自
views/layouts/main.handlebars
的
HTML
样板代码。
即使每次访问主页得到的都是同样的
HTML
,这些路由也是
动态内容
,因为每次调用路由
时,我们都可以做出不同的决策(在本书后面章节中将看到很多这样的例子)。不过,永
远不变化的内容(也就是静态内容)也是很常见的,所以接下来讲一下静态内容。
3.5
 静态文件与视图
Express
依靠
中间件
来处理静态文件和视图。第
10
章将详细讨论中间件这个概念。就现在
来说,只要知道中间件提供模块化的功能,简化了请求处理,就够了。
static
这个中间件允许你指定一个或多个包含静态资源的目录,里面的资源会不加任何特
别处理,直接发送给客户端。这些目录就是你放入图片、
CSS
文件和客户端
JavaScript
文
件的地方。
在项目目录下,创建一个名为
public
的子目录
(称其为
public
是因为这个目录下的任何东
西都可以不经询问而发给客户端)。然后,在声明任何路由前,加入 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

面向对象的思考过程(原书第5版)

面向对象的思考过程(原书第5版)

马特 魏斯费尔德
精通模块化JavaScript

精通模块化JavaScript

Nicolás Bevacqua
前端架构设计

前端架构设计

Micah Godbolt

Publisher Resources

ISBN: 9787115565099