configuring express for ejs

  1. https://ejs.co/
  2. mkdir test

  3. cd test
  4. npm init -y
  5. npm i express
  6. touch index.js
  7. npm i ejs
  8. mkdir views
  9. touch views/home.ejs
  10. nodemon index.js
index.js
const express = require(‘express‘); const app = express(); // tell my app to use express, the teacher is ejs // we don‘t need to require ejs, just set the engine view to ejs app.set(‘view engine‘, ‘ejs‘) app.get(‘/‘, (req, res) => { res.render(‘home.ejs‘) //默认路径就是在views文件夹下,不用加views/home.ejs }) app.listen(3000, () => { console.log("Listening On Port 3000") })
home.ejs

<!
DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Home</title> </head> <body> <h1>《出现又离开》</h1> <p> 试探未知和未来 <br> 相信那胡言一派 <br> 当天空暗下来<br> 当周围又安静起来<br> 当我突然梦里醒来<br> 就等着太阳出来<br> </p> </body> </html>

configuring express for ejs

如果我们在项目文件的外面的路径运行整个程序会出错:那么如果我们想在任何地方正常运行这个程序呢?

——use views directory

configuring express for ejs

index.js

const express = require(‘express‘);
const app = express();
const path = require(‘path‘);

// tell my app to use express, the teacher is ejs
// we don‘t need to require ejs, just set the engine view to ejs
app.set(‘view engine‘, ‘ejs‘)
app.set(‘views‘, path.join(__dirname, ‘/views‘))   //__dirname is where index.js is located

app.get(‘/‘, (req, res) => {
    res.render(‘home.ejs‘)
})

app.listen(3000, () => {
    console.log("Listening On Port 3000")
})

configuring express for ejs

then it will work fine.

configuring express for ejs

上一篇:用 httpClient 连接 https 服务端,不校验证书的 host


下一篇:CentOS Inatall Rancher & Kubernetes