nodejs article express (4) express + art-template to create the basis of the website

foreword

insert image description here

In order to apply to more and more complex website business and user interaction, the front and back ends have been separated for many years, but at the beginning of web development, there was no mvvm framework such as vue and react, and there was no so-called single page response (SPA) , how is the rendering of the web page realized?

The resources required by a website are uniformly read by the server directly in the local library (take index.html as an example), and then, according to different users, replace the text in the read file index.html.

Of course, in addition to html, the server will also return all the static resources required by the website, css, js, font icons and so on.

Today, the server is established through express, the file is read by the fs module of node, and then the art-template template engine is used to realize the binding of the html file and the data, and put it into the interface to return.

template engine

In fact, there are many template engines, ejs and art-template are relatively easy to use, and these two are relatively well-known.

ejs official website: https://ejs.bootcss.com/
art-template official website: http://aui.github.io/art-template/zh-cn/docs/

The implementation principle of the template engine is actually very simple, that is, in HTML, specific positions are marked with specific symbols, such as:

// index.html
<div>
	<h1>TODOS</h1>
	<ul>^-^</ul>
</div>
var express = require("express");
var fs = require("fs");

var app = express();
var PORT = process.env.PORT || 3000;

app.get("/", function (req, res) {
    
    
  var todos = [{
    
     title: "title1" }, {
    
     title: "title2" }];

  // 读取html文件,记得使用utf8的方式,否则读取的是二进制流数据而不是字符串数据
  fs.readFile("./index.html", "utf8", (err, data) => {
    
    
    var str = "";
    todos.forEach((todo) => {
    
    
      str += `<li>${
      
      todo.title}</li>`;
    });
    // 找到标记并完成替换
    const result = data.replace("^-^", str);
    // 通过接口返回
    res.end(result);
  });
});

app.listen(PORT, function () {
    
    
  console.log(`server runing at ${
      
      PORT}`);
});

In actual business, we need more complex tags, in addition to loops and conditions, we even need to introduce dynamic external resources, write js code directly in html, etc., and all these are done by the template engine for us.

install art-template

npm i art-template --save

basic use

Use the syntax of art-template to transform the html file

// index.html
<div>
	<h1>TODOS</h1>
	<ul>
		{
   
   { each todos }}
		<li>{
   
   { $value.title }}</li>
		{
   
   { /each }}
	</ul>
</div>

Using art-template in the express interface

var express = require("express");
var fs = require("fs");
var template = require("art-template")

var app = express();
var PORT = process.env.PORT || 3000;

app.get("/", function (req, res) {
    
    
  var todos = [{
    
     title: "title1" }, {
    
     title: "title2" }];

  // 读取html文件,记得使用utf8的方式,否则读取的是二进制流数据而不是字符串数据
  fs.readFile("./index.html", "utf8", (err, templateStr) => {
    
    
    
    // 通过art-template完成模板与数据的绑定
    const result = template.render(templateStr, {
    
     todos });
    // 通过接口返回
    res.end(result);
  });
});

app.listen(PORT, function () {
    
    
  console.log(`server runing at ${
      
      PORT}`);
});

art-template more syntax http://aui.github.io/art-template/zh-cn/docs/syntax.html

Use art-template in the project

art-template can be integrated in express, which makes it more convenient for us developers to use in practice.

Install express-art-template

npm install --save express-art-template

The html template file has been placed in the views folder

var express = require("express");
var path = require("path");

var app = express();
var PORT = process.env.PORT || 3000;

app.engine('html', require('express-art-template')); // 当渲染以.html 结尾的资源文件,使用express-art-template, 更多配置 http://aui.github.io/art-template/docs/options.html
app.set('view options', {
    
     // express-art-tempalte 配置
    debug: process.env.NODE_ENV !== 'production'
});
app.set('views', path.join(__dirname, 'views')); // 模板文件存储的目录
app.set('view engine', 'html'); // 可以省略的模板文件名后缀

// 只要使用了以上的配置,就可以在使用res.render方法

app.get("/", function (req, res) {
    
    
  var todos = [{
    
     title: "title1" }, {
    
     title: "title2" }];

  // 读取html文件,记得使用utf8的方式,否则读取的是二进制流数据而不是字符串数据
//   fs.readFile("./views/index.html", "utf8", (err, data) => {
    
    
//     var str = "";
//     todos.forEach((todo) => {
    
    
//       str += `<li>${todo.title}</li>`;
//     });
//     // 找到标记并完成替换
//     const result = data.replace("^-^", str);
//     // 通过接口返回
//     res.end(result);
//   });

    res.render('index.html',{
    
    
        todos
    })
});

app.listen(PORT, function () {
    
    
  console.log(`server runing at ${
      
      PORT}`);
});

static resource management

A website cannot only have html files, we also need to introduce css, js, img, video, and other static resources.

To do a unified management, create a public folder in the root directory of the project, and create js, css, img and other file names under the folder according to the file type.

Modify the following view/index.html and introduce some static resources

// views/index.html
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

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

<body>
    <div>
        <h1>TODOS</h1>
        <ul>
            {
   
   { each todos }}
            <li>{
   
   { $value.title }}</li>
            {
   
   { /each }}
        </ul>
        <img src="/public/img/https.png" />
    </div>
</body>

</html>
<!-- /是指的绝对地址,在http协议中,相对于当前的url地址,比如下面的资源将会请求 localhost:3000/public/js/index.js -->
<!-- 我们在express中配置了 /public 的请求,就去 绝对地址的/public文件夹下寻找 -->
<script src="/public/js/index.js"></script>

referenced css file

// public/css/index.css
li {
    
    
    list-style-type: none;
}

reference js file

// public/js/index.js
console.log('hello world')
// app.js
var express = require("express");
var path = require("path");

var app = express();
var PORT = process.env.PORT || 3000;

app.engine("html", require("express-art-template")); // 当渲染以.html 结尾的资源文件,使用express-art-template
app.set("view options", {
    
    
  // express-art-tempalte 配置
  debug: process.env.NODE_ENV !== "production",
});
app.set("views", path.join(__dirname, "views")); // 模板文件存储的目录
app.set("view engine", "html"); // 可以省略的模板文件名后缀

// 只要使用了以上的配置,就可以在使用res.render方法

app.get("/", function (req, res) {
    
    
  var todos = [{
    
     title: "title1" }, {
    
     title: "title2" }];

  res.render("index", {
    
    
    todos,
  });
});

// 当资源请求以/public 开头时,去public文件夹中寻找对应的文件并返回,此处尽量使用绝对地址
// express.static 是express自带的中间件之一,用来处理静态资源文件的,更多配置和使用方式  https://expressjs.com/zh-cn/4x/api.html#express

var options = {
    
    
  // dotfiles: 'ignore',
  // etag: false,
  // extensions: ['htm', 'html'],
  // index: false,
  // maxAge: '1d',
  // redirect: false,
  // setHeaders: function (res, path, stat) {
    
    
  //   res.set('x-timestamp', Date.now())
  // }
};

// 如果有多个静态资源,出现在上面的代码会优先匹配,即放在public文件夹下的静态资源会优先匹配
app.use("/public", express.static(path.join(__dirname, "./public"), options));
// app.use("/static",express.static(path.join(__dirname, "./public")))

app.listen(PORT, function () {
    
    
  console.log(`server runing at ${
      
      PORT}`);
});

Through the picture below, all static resources are loaded successfully.
insert image description here

Other content related to nodejs

nodejs commonjs introduces
nodejs fs module introduces
nodejs path module introduces
nodejs events module introduces
nodejs http module introduces nodejs
net module introduces
nodejs url module introduces
nodejs process module introduces
nodejs buffer module introduces
nodejs stream module introduces
nodejs express (1) module introduces
nodejs express (2 ) Middleware Detailed
Nodejs Express (3) Interface Service Framework

Guess you like

Origin blog.csdn.net/glorydx/article/details/129988790