我的express.js项目中有这个错误:
Error: Failed to lookup view "error" in views directory
我想通过一条路线重定向到一个html页面。
我创建了一个表单,用于发送路径 inserToDB 的名称和姓氏。 我想重新定位 profile.ejs 页面,但我总是发现此错误。
我不明白原因。所以我会发布我的代码,希望你能帮助我..
app.js
var routes = require('./routes/routes');
var users = require('./routes/users');
var app = express();
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// view engine setup
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
route.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res) {
console.log("index.ejs è caricata!");
res.render('index.ejs');
});
router.get('/profile', function(req, res) {
console.log("Ok ci siamo: profile caricata!");
res.render('profile.ejs');
});
router.get('/insertToDB', function(req, res) {
console.log(req.query.name + req.query.surname);
res.redirect("/profile");
});
module.exports = router;
index.ejs
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<script type="text/javascript" src="js/jquery.js"></script>
</head>
<body>
Ciao loschi!
Inserisci i tuoi dati
<div>
Nome <input type="text" name="name" id="name"></input>
<br>
Cognome<input type="text" name="surname" id="surname"></input>
<br>
<input type="submit" name="Invia" id="enter"></input>
<script type="text/javascript" src="js/action.js"></script>
</div>
</body>
</html>
action.js
$("#enter").on("click", function(){
var name = $("#name").val();
var surname = $("#surname").val();
$.ajax({
type: "get",
url: "/insertToDB",
data:"name=" + name +"&surname="+ surname,
async:"true"
});
});
答案 0 :(得分:0)
尝试将app.js
中的引擎设置更改为:
// view engine setup
app.engine('html', require('ejs').renderFile);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');
然后将app.js
中的错误处理程序更改为:
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error.ejs');
});
不要忘记在views目录中创建一个名为.ejs
的{{1}}文件。这应该可以修复错误。