美文网首页
express高效入门教程(4)

express高效入门教程(4)

作者: 螺钉课堂 | 来源:发表于2019-12-24 10:28 被阅读0次

    4.静态文件

    #4.1.普通处理静态文件的方法

    在./views/index.html文件中去引入另一个css文件index.css,index.css文件放在public/css目录下,目录结构是这样的

    image

    index.html文件中的内容

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>Document</title>
      <style>
        #wrap {
          width: 300px;
          margin: 100px auto;
          line-height: 150px;
          height: 150px;
          text-align: center;
          background-color: green;
        }
        #wrap a {
          color: white;
          text-decoration: none;
        }
      </style>
      <link rel="stylesheet" href="/public/css/index.css">
    </head>
    <body>
      <div id="wrap">
          <a href="/login">登录 | </a>
          <a href="/user">用户中心</a>
      </div>
    </body>
    </html>
    
    

    根据请求渲染出index.html文件

    app.get('/', function (req, res) {
      res.sendFile('./index.html')
    })
    
    

    当我们方法 '/'这个路径的时候,能把index.html页面加载出来,但是没办法把css文件加载出来

    image

    为了解决这个问题,我们还需要单独去写一个路由去返回css文件

    app.get('/public/css/index.css', function (req, res) {
      res.sendFile(path.resolve('./public/css/index.css'))
    })
    
    

    #4.2.express中处理静态文件的插件

    express中提供了处理静态文件的插件,这里的静态文件就是我们项目中需要用到的img、css、js等资源,只需要简单的配置就可以实现对静态文件的处理,步骤如下:

    第一步,在app中挂载插件

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

    第二步,使用静态文件,在index.html文件中引入css,路径需要修改一下

    <link rel="stylesheet" href="/css/index.css">
    

    相关文章

      网友评论

          本文标题:express高效入门教程(4)

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