NodeJs

Nodejs 返回动态的Html

Nodejs express 也可以返回动态的Html,下面是Sample代码。

  • Html代码
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport"
    content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no" />
  <meta name="apple-mobile-web-app-capable" content="yes" />
  <link rel="icon" href="<%= BASE_URL %>favicon.ico">
  <style type="text/css">
  </style>

  <title>HelloWorld</title>
</head>

<body bgcolor="#F1F1F1">

  <div>
    
      <div>
        // URL1是需要被替换的内容
        <a href="URL1" target="_blank">
          HelloWorld1
        </a>
      </div>
      <div>
       // URL2是需要被替换的内容
       <a href="URL2" target="_blank">
          HelloWorld2
        </a>
      </div>
  </div>

</body>

</html>
  • router.js
const express = require('express');
const router = express.Router();
const fs = require('fs');

/*
 *@method index画面ページを取得する
 *@return index画面Html
 */
router.get('/index', function (req, res) {

  let indexHtml = fs.readFileSync('./index.html', 'utf8');
  indexHtml = indexHtml.replace("URL1", "http://www.163.com");
  indexHtml = indexHtml.replace("URL2", "http://www.baidu.com");
  res.end(indexHtml);

});

module.exports = router;