美文网首页
利用express托管静态文件

利用express托管静态文件

作者: 未vv | 来源:发表于2020-03-20 20:52 被阅读0次

    使用 Express 中的 express.static 内置中间件函数,提供诸如图像、CSS 文件和 JavaScript 文件之类的静态文件

    express.static(root, [options])  //这实际上是express的内置中间件
    

    通过app.use()使用中间件。例如,通过如下代码就可以将 public 目录下的图片、CSS 文件、JavaScript 文件对外开放访问了:

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

    现在,你就可以访问 public 目录中的所有文件了:

    http://localhost:3000/images/kitten.jpg
    http://localhost:3000/css/style.css
    http://localhost:3000/js/app.js
    http://localhost:3000/images/bg.png
    http://localhost:3000/hello.html
    

    Express 在静态目录查找文件,因此,存放静态文件的目录名不会出现在 URL 中。
    如果要使用多个静态资源目录,请多次调用 express.static 中间件函数:

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

    要为express.static函数所服务的文件创建虚拟路径前缀(文件系统中实际上不存在该路径),请为静态目录指定安装路径:

    app.use('/static', express.static('public'))
    

    现在,你就可以通过带有 /static 前缀地址来访问 public 目录中的文件了。

    http://localhost:3000/static/images/kitten.jpg
    http://localhost:3000/static/css/style.css
    http://localhost:3000/static/js/app.js
    http://localhost:3000/static/images/bg.png
    http://localhost:3000/static/hello.html
    

    相关文章

      网友评论

          本文标题:利用express托管静态文件

          本文链接:https://www.haomeiwen.com/subject/tzssyhtx.html