问题
I am learning NodeJS and have built a very simple app that renders an EJS template passing a string variable. When I try to run it however, it says the variable "greeting" is undefined:
app.js:
var express = require("express");
var app = express();
app.set("view engine", "ejs");
app.get('/', function(req, res) {
res.render("index.ejs", {
greeting: "Hello World"
});
});
app.listen(3000);
index.ejs:
<h1>Testing out EJS</h1>
<h2>Greeting is: <%= greeting %></h2>
Any ideas as to why this doesn't work?
回答1:
So I found out that the solution here was much simpler than I thought. If you're running your server while making changes to project files the changes will not necessarily get picked up. In order to avoid this, every change needs to be followed by a server restart.
With that being said, a tool called Nodemon (https://github.com/remy/nodemon) is helpful for development, as it restarts the server for you automatically following a change.
来源:https://stackoverflow.com/questions/26368693/simple-variable-passed-into-ejs-template-is-undefined