无法在视图目录中查找视图“索引”快递| HBS代替handlebars.js

时间:2019-11-09 17:11:04

标签: node.js express handlebars.js

view-engine

我已经安装了hbs而不是把手来进行动态模板制作,现在我陷入了这个问题。

Error: Failed to lookup view "index" in views directory "/home/trijay/Desktop/NodeJs/web-server/src/views"
    at Function.render (/home/trijay/Desktop/NodeJs/web-server/node_modules/express/lib/application.js:580:17)
    at ServerResponse.render (/home/trijay/Desktop/NodeJs/web-server/node_modules/express/lib/response.js:1008:7)
    at app.get (/home/trijay/Desktop/NodeJs/web-server/src/app.js:14:9)
    at Layer.handle [as handle_request] (/home/trijay/Desktop/NodeJs/web-server/node_modules/express/lib/router/layer.js:95:5)
    at next (/home/trijay/Desktop/NodeJs/web-server/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/home/trijay/Desktop/NodeJs/web-server/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/home/trijay/Desktop/NodeJs/web-server/node_modules/express/lib/router/layer.js:95:5)
    at /home/trijay/Desktop/NodeJs/web-server/node_modules/express/lib/router/index.js:281:22
    at Function.process_params (/home/trijay/Desktop/NodeJs/web-server/node_modules/express/lib/router/index.js:335:12)
    at next (/home/trijay/Desktop/NodeJs/web-server/node_modules/express/lib/router/index.js:275:10)

下面是我的app.js代码,并且我已经安装了hbs Express库。任何帮助将不胜感激

// app.js

const express = require('express')
const path = require('path')


const publicPath = path.join(__dirname, '../public')   //for accessing comeplete file

const app = express()   //express being initialised


app.use(express.static(publicPath))
app.set('view engine', 'hbs')    //use to set handle bars. we need to provide key value pair

app.get('', (req, res) => {
    res.render('index')             //need to provide the hbs file name which you will find in view
})


app.get('/weather', (req, res) => {
    res.send({
        latitude: -57.89,
        longitude: 78.42,
        location : 'New Delhi'
    })

})

app.listen(3000, () => {
    console.log('Server Started on port 3000')
})

2 个答案:

答案 0 :(得分:0)

我认为您可能在定义引擎后忘记设置引擎。

app.set('view engine', 'hbs');

app.engine( 'hbs', hbs( {
  extname: 'hbs',
  defaultView: 'index' //your default template
}));

尝试一下,让我知道。

答案 1 :(得分:0)

views目录添加到引擎选项:

app.set('view engine', 'hbs') 
app.set('views', path.join(__dirname, '../views'));

您会在错误消息中看到:

Error: Failed to lookup view "index" in views directory "/home/trijay/Desktop/NodeJs/web-server/src/views"

res.render('index')指向src目录中的某个地方。