nodejsの記事 express(4) express + art-templateでサイトの土台を作る

序文

ここに画像の説明を挿入

ますます複雑化するWebサイトのビジネスやユーザーとのやり取りに対応するために、フロントエンドとバックエンドは長年分離されてきましたが、Web開発の初期にはvueやreactなどのmvvmフレームワークがなく、いわゆるシングル ページ レスポンス (SPA) では、Web ページのレンダリングはどのように実現されますか?

Web サイトに必要なリソースは、ローカル ライブラリ (例として index.html を取り上げます) でサーバーによって一様に直接読み取られ、次に、さまざまなユーザーに応じて、読み取られたファイル index.html 内のテキストを置き換えます。

もちろん、html に加えて、サーバーは Web サイト、css、js、フォント アイコンなどに必要なすべての静的リソースも返します。

現在、サーバーはexpressを介して確立され、ノードのfsモジュールによってファイルが読み取られ、art-templateテンプレートエンジンを使用してhtmlファイルとデータのバインディングが実現され、それを返すインターフェイスに入れられます.

テンプレートエンジン

実際、テンプレートエンジンはたくさんありますが、ejs と art-template は比較的使いやすく、この 2 つが比較的よく知られています。

ejs公式サイト:https://ejs.bootcss.com/
art-template公式サイト:http://aui.github.io/art-template/zh-cn/docs/

テンプレート エンジンの実装原理は実際には非常に単純です。つまり、HTML では、特定の位置が次のような特定の記号でマークされます。

// 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}`);
});

実際のビジネスでは、ループや条件に加えて、より複雑なタグが必要であり、動的な外部リソースを導入したり、js コードを html に直接記述したりする必要がありますが、これらはすべてテンプレート エンジンによって行われます。

アートテンプレートをインストールする

npm i art-template --save

基本的な使い方

art-template の構文を使用して、html ファイルを変換します

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

エクスプレス インターフェイスでの art-template の使用

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 より多くの構文http://aui.github.io/art-template/zh-cn/docs/syntax.html

プロジェクトでアート テンプレートを使用する

art-template は Express に統合できるため、私たち開発者が実際に使用するのがより便利になります。

express-art-template をインストールする

npm install --save express-art-template

html テンプレート ファイルはビュー フォルダーに配置されています。

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}`);
});

静的リソース管理

Web サイトは html ファイルだけではなく、css、js、img、video、およびその他の静的リソースも導入する必要があります。

一元管理するには、プロジェクトのルート ディレクトリに public フォルダーを作成し、そのフォルダーの下に、ファイルの種類に応じて js、css、img などのファイル名を作成します。

次の view/index.html を変更し、いくつかの静的リソースを導入します

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

参照されたcssファイル

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

jsファイルを参照

// 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}`);
});

以下の図から、すべての静的リソースが正常にロードされています。
ここに画像の説明を挿入

nodejsに関連するその他のコンテンツ

nodejs commonjs を導入
nodejs fs モジュールを導入
nodejs パス モジュールを導入
nodejs イベント モジュールを導入
nodejs http モジュールを導入 nodejs
netモジュールを導入
nodejs url モジュールを導入
nodejs プロセス モジュールを導入
nodejs バッファ モジュールを導入 nodejs
ストリーム モジュールを導入
nodejs express (1) モジュールを導入
nodejs express (2 ) ミドルウェア 詳細
Nodejs Express (3) インターフェイス サービス フレームワーク

おすすめ

転載: blog.csdn.net/glorydx/article/details/129988790