express efficient introductory tutorial (4)

4. Static file

4.1. The common method of handling static files

In ./views/index.html css file to another file introduced index.css, index.css file in the public / css directory, the directory structure is such that

Content in the index.html file

<!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>

According to the request to render the index.html file

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

When our approach '/' This path can index.html page loads out, but no way to load up css file

To solve this problem, we also need to write a separate route to return css file

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

4.2.express plug-in static files

express provides plug-in processing static files, static files here is that we need to use the project img, css, js and other resources, need only a simple configuration process for static files can be achieved by following these steps:

The first step, the mount plug-in app

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

The second step, using static files, css introduced in the index.html file, the path need to change

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

Screw classroom video lessons Address: http://edu.nodeing.com

Guess you like

Origin www.cnblogs.com/dadifeihong/p/12047903.html