- https://ejs.co/
-
mkdir test
- cd test
- npm init -y
- npm i express
- touch index.js
- npm i ejs
- mkdir views
- touch views/home.ejs
- 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>
如果我们在项目文件的外面的路径运行整个程序会出错:那么如果我们想在任何地方正常运行这个程序呢?
——use views directory
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") })
then it will work fine.