expressjs 框架:访问静态文件

说明

express 支持静态文件:当浏览器访问静态文件时,可以直接返回该文件的内容

静态文件包括:HTML、图片, CSS, JavaScript 等

api

使用 express.static 设置静态文件路径

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

例子

创建 public 文件夹,将 index.html、图片、CSS、.js 文件放在 public 目录下

目录结构如下:

/工程文件夹
    /public
        /index.html
        /style.css
        /script.js
        /404.html
    /index.js

设置静态文件路径(不指定路由)

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

// 设置静态文件路径,默认就是 '/' 路由
app.use(express.static(path.join(__dirname, 'public')));

// 设置静态文件路径,指定 '/static' 路由
app.use('/static', express.static(path.join(__dirname, 'public')));

// 启动服务,监听端口
const server = app.listen(port, function () {

  // var host = server.address().address
  // var port = server.address().port

  console.log("服务启动成功,监听端口是", port)

})
访问

打开浏览器,如果 public 文件夹内有 index.html,可以通过 URL 直接访问:

http://localhost:8081/

设置静态文件路径(指定路由)

指定 /static 路由,增加下面代码

app.use('/static', express.static(path.join(__dirname, 'public')));
访问

打开浏览器,如果 public 文件夹内有 index.html,可以通过 URL 直接访问:

http://localhost:8081/static/

注意:后面要加上 static

找不到资源时返回 404 页面

提出问题

访问不存在的资源时,如:

http://localhost:8081/asdf

页面显示如下:

Cannot GET /asdf

用户看不懂英文,很不友好

解决

创建 404.html 文件

内容如下:

<h2>404找不到资源</h2>

指定404错误时,发送 404.html 文件

app.use((req, res) => {
  // res.status(404).send('404 Not Found')
  res.status(404).sendFile(path.join(__dirname, 'public/404.html'))
})

参考:
https://blog.csdn.net/zz00008888/article/details/144242679


原文出处:/show_1GWMqRlecQ2.html