我正在尝试使用ejs视图引擎,以便可以访问URL末尾没有.html扩展名的文件。但是,我得到一个错误。
const express = require('express')
const app = express()
const path = require('path')
app.set("view engine", "ejs");
app.use(express.static(__dirname + '/public'));
app.use('/', express.static('views/statics'));
const PORT = process.env.PORT || 3000;
app.listen(PORT,() => {
console.log(`Server is listening on port ${PORT}`)
});
app.get('/case/:case',(req,res,next)=> {
res.sendFile(req.params.case, { root: path.join( __dirname, 'views/statics/case')})
})
错误
当我尝试访问http://localhost:3000/case/firstcase
Error: ENOENT: no such file or directory, stat '.../app/views/statics/case/firstcase'
在首字母大写结尾处不附加.ejs
答案 0 :(得分:0)
server.js
const express = require('express')
const app = express()
const path = require('path')
app.set('views', path.join(__dirname, 'app/views')) // call folder views is folder name.
app.set("view engine", "ejs");
app.use(express.static(__dirname + '/public'));
//app.use('/', express.static('views/statics'));
const PORT = process.env.PORT || 3000;
app.listen(PORT,() => {
console.log(`Server is listening on port ${PORT}`)
});
app.get('/case/:case',(req,res,next)=> {
//res.sendFile(req.params.case, { root: path.join( __dirname, 'views/statics/case')})
res.render('statics/case/firstcase',{case : req.params.case});
})
app/views/statics/case/firstcase
<!DOCTYPE html>
<html lang="en">
<head>
<body>
<body>
<h1><%= case%></h1>
</body>
<html>
答案 1 :(得分:0)
目录结构:
- views
----- partials
---------- footer.ejs
---------- head.ejs
---------- header.ejs
----- pages
---------- index.ejs
---------- about.ejs
- package.json
- server.js
这是server.js:
var express = require('express');
var app = express();
// set the view engine to ejs
app.set('view engine', 'ejs');
app.set('views',`${__dirname}/views`);
// use res.render to load up an ejs view file
// index page
app.get('/', function(req, res) {
res.render('pages/index');
});
// about page
app.get('/about', function(req, res) {
res.render('pages/about');
});
app.listen(8080);