express高效入门教程(4)

4.静态文件

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

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

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文件加载出来

为了解决这个问题,我们还需要单独去写一个路由去返回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">

螺钉课堂视频课程地址:http://edu.nodeing.com

猜你喜欢

转载自www.cnblogs.com/dadifeihong/p/12047903.html