SyntaxError:编译ejs时出现意外令牌

时间:2019-09-01 06:07:58

标签: node.js ejs

我刚刚开始学习Node JS。呈现ejs文件时,出现了意外的令牌错误。有人帮我解决这个错误。我的代码如下:

错误:

SyntaxError: Unexpected token { in C:\Users\Ghulam Abbas\Desktop\Node\Conditionals\views\blogpost.ejs while compiling ejs

If the above error is not helpful, you may want to try EJS-Lint:
https://github.com/RyanZim/EJS-Lint
Or, if you meant to create an async function, pass async: true as an option.
at new Function (<anonymous>)
at Template.compile (C:\Users\Ghulam Abbas\Desktop\Node\Conditionals\node_modules\ejs\lib\ejs.js:633:12)
at Object.compile (C:\Users\Ghulam Abbas\Desktop\Node\Conditionals\node_modules\ejs\lib\ejs.js:392:16)
at handleCache (C:\Users\Ghulam Abbas\Desktop\Node\Conditionals\node_modules\ejs\lib\ejs.js:215:18)
at tryHandleCache (C:\Users\Ghulam Abbas\Desktop\Node\Conditionals\node_modules\ejs\lib\ejs.js:254:16)
at View.exports.renderFile [as engine] (C:\Users\Ghulam Abbas\Desktop\Node\Conditionals\node_modules\ejs\lib\ejs.js:485:10)
at View.render (C:\Users\Ghulam Abbas\Desktop\Node\Conditionals\node_modules\express\lib\view.js:135:8)
at tryRender (C:\Users\Ghulam Abbas\Desktop\Node\Conditionals\node_modules\express\lib\application.js:640:10)
at Function.render (C:\Users\Ghulam Abbas\Desktop\Node\Conditionals\node_modules\express\lib\application.js:592:3)
at ServerResponse.render (C:\Users\Ghulam Abbas\Desktop\Node\Conditionals\node_modules\express\lib\response.js:1012:7) 

app.js

var express = require('express');
var app = express();

app.get('/', function(req, res) {
    res.send('Blog Homepage.');
});

app.get('/posts', function(req, res) {

    res.render('blogpost.ejs', {posts : "posts"});

});


app.listen(3000, function() {
    console.log("Server is started.");
});

blogpost.ejs

<h1>Blog <%= posts %> </h1>

谢谢。

2 个答案:

答案 0 :(得分:1)

我只是更新您的代码,似乎您忘记了设置视图引擎

var express = require('express');
var app = express();
var path = require('path');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.get('/', function(req, res) {
    res.send('Blog Homepage.');
});

app.get('/posts', function(req, res) {

    res.render('blogpost.ejs', {posts : "posts"});

});


app.listen(3000, function() {
    console.log("Server is started.");
});

请确保您运行npm i ejs。 并且您可能需要将所有视图文件存储在一个文件夹中,以便更清楚地了解文件夹结构。在此代码中,请将您的blogpost.ejs移至views文件夹。希望对您有帮助

答案 1 :(得分:0)

$('#link').prop('value', 'new value');