xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

Node.js express server render HTML template All In One

Node.js express server render HTML template All In One

HTML 模版引擎

Template Engine

https://expressjs.com/en/guide/using-template-engines.html

https://expressjs.com/en/advanced/developing-template-engines.html

jade / pug / ejs

# old version, jade
# new version, pug
$ npm i pug
# OR
$ yarn add pug

https://pugjs.org/api/getting-started.html

$ npm i ejs

$ npm i jade

https://www.npmjs.com/package/pug
https://www.npmjs.com/package/jade
https://www.npmjs.com/package/ejs

https://www.npmjs.com/package/mustache

demos

/**
* express static server for react build/dist test!
*/

// simple express server for HTML pages!
// ES6 style

const express = require('express');
// const bodyParser = require('body-parser');
const fs = require('fs');
const hostname = '127.0.0.1';
const port = 3000;
const app = express();
// Starting with release 4.16.0, a new express.json() middleware is available.
app.use(express.json());
app.use(express.urlencoded({
  extended: true,
}));

app.use(express.static(__dirname + '/public'));

// 模版引擎 views
app.set('views', './views');
app.set('view engine', 'pug');

// parse application/json
// app.use(bodyParser.json());
// parse application/x-www-form-urlencoded, multipart/form-data
// app.use(bodyParser.urlencoded({ extended: true }));


// let cache = [];// Array is OK!
// cache[0] = fs.readFileSync( __dirname + '/index.html');
// cache[1] = fs.readFileSync( __dirname + '/views/testview.html');

// app.get('/', (req, res) => {
//     res.setHeader('Content-Type', 'text/html');
//     res.send( cache[0] );
// });

// app.get('/test', (req, res) => {
//     res.setHeader('Content-Type', 'text/html');
//     res.send( cache[1] );
// });

// https://www.runoob.com/nodejs/nodejs-express-framework.html

app.use(function (req, res, next) {
  // JSON parse
  // console.log('req.body', req.body);
  // logger
  // 获取主机名和IP地址
  console.log('req.ip =', req.ip);
  console.log('req.hostname =', req.hostname);
  // 获取原始请求URL
  console.log('req.originalUrl =', req.originalUrl);
  next();
});


app.get('/', function (req, res) {
  res.render('index', {
    title: 'pug template engine 🚀',
    message: '🐶 Hello Pug!',
  });
});
// http://127.0.0.1:3000/api/get?q={'key':'value'}
// http://127.0.0.1:3000/api/get?q={key:'value'}

// http://127.0.0.1:3000/api/get?q=%7B%22username%22:%22xgqfrms%22%7D

app.get('/api/get', (req, res) => {
    // console.log('get req', req);
    console.log('req.params', req.params);
    console.log('req.query', req.query, req.query.q);
    // console.log('req.query', req.query, JSON.stringify(JSON.parse(req.query), null, 4));
    const obj = JSON.parse(req.query.q);
    console.log('obj =', JSON.stringify(obj, null, 4));
    res.setHeader('Content-Type', 'text/html');
    res.send('get api');
});

app.post('/api/post', (req, res) => {
  // console.log('❌ post req', req);
  console.log('✅ post req.body', req.body);
  // res.setHeader('Content-Type', 'text/html');
  // res.send('get api');
  res.sendStatus(200);
});

// http://127.0.0.1:3000/api/post
// {key: "value"}

app.post('/api/post', (req, res) => {
    console.log('post req', req);
    console.log('post req', req.params, req.query);
    res.setHeader('Content-Type', 'application/json');
    res.send({res: 'post api'});
});


app.listen(port, () => {
    console.log(`
        Server is running at http://${hostname}:${port}/
        Server hostname ${hostname} is listening on port ${port}!
    `);
});


fetch(`http://127.0.0.1:3000/api/post`, {
    body: JSON.stringify({key: "value"}),
    cache: "no-cache",
    headers: {
        "Content-Type": "application/json",
    },
    method: "POST", // *GET, POST, PUT, DELETE, etc.
    mode: "no-cors",
})
.then(res => console.log(`res =`, res))
.catch(err => console.error(`error =`, err));


http://127.0.0.1:3000/

http://127.0.0.1:3000/api/get?q={"username":"xgqfrms"}



(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

express.js

4.17.1

https://expressjs.com/zh-cn/

5.0.0-alpha.8

https://expressjs.com/en/guide/migrating-5.html

HTML2Jade

HTML to Jade/Pug Online Realtime Converter

https://html2jade.org/

doctype html
html(lang='zh-Hans')
  head
    title= title
  body
    h1= message
    section#app
      a(href="http://127.0.0.1:3000/api/get?q=%7B%22username%22:%22xgqfrms%22%7D") http://127.0.0.1:3000/api/get?q=%7B%22username%22:%22xgqfrms%22%7D


middleware

https://github.com/expressjs/serve-static

// 


refs



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2021-04-20 22:22  xgqfrms  阅读(52)  评论(5编辑  收藏  举报