英文:
EJS is not working when I use a variable that is passed from server
问题 {#heading}
ESJ 代码: {#esj-}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>待办事项列表</title>
<link rel="stylesheet" href="public\styles.css" />
<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-4bw+/aepP/YC94hEpVNVgiZdgIC5+VKNBQNGCHeKRQN+PtmoHDEXuppvnDJzQIu9"
crossorigin="anonymous"
/>
<script
src="https://kit.fontawesome.com/20accab6ba.js"
crossorigin="anonymous"
></script>
</head>
<body>
<div
class="d-flex flex-column flex-md-row p-4 gap-4 py-md-5 align-items-center justify-content-center"
>
<div class="list-group">
<form
class="list-group-item d-flex gap-3 bg-body-tertiary"
action="/submit"
method="POST"
>
<span class="pt-1 form-checked-content">
<span contenteditable="true" class="w-100" id="taskInput">
<input
type="text"
id="task"
name="task"
placeholder="输入您的任务"
/>
</span>
<small class="d-block text-body-secondary">
<i
class="fa-regular fa-clock bi me-1"
width="1em"
height="1em"
style="color: #7a8290"
></i>
<input type="time" id="time" name="time" />
</small>
</span>
<%= variable %>
<button class="btn btn-primary" type="submit">提交</button>
</form>
</div>
</div>
</body>
</html>
服务器代码: {#heading-1}
import express from "express";
import bodyParser from 'body-parser';
import ejs from "ejs";
import { dirname } from "path";
import { fileURLToPath } from "url";
const app = express();
const port = 3000;
const __dirname = dirname(fileURLToPath(import.meta.url));
const currentTime = new Date();
const hours = currentTime.getHours();
const minutes = currentTime.getMinutes();
app.use(express.static("public"));
app.use(bodyParser.urlencoded({ extended: true }));
app.get("/", (req, res) => {
res.render(`${__dirname}/views/index.ejs`);
});
app.post('/submit', (req, res) => {
res.render(`${__dirname}/views/index.ejs`, {
variable: "你好",
});
});
app.listen(port, () => {
console.log("服务器已启动,端口:" + port);
});
错误: {#heading-2}
ReferenceError: C:\Users\Niklaus\Desktop\Web Develepment Course\BackEnd\4.5 Capstone Prject To-Do-List\views\index.ejs:26
24|25|
26| <%= variable %>
27|
28| 提交
29|
variable is not defined
at eval (eval at compile (C:\Users\Niklaus\Desktop\Web Develepment Course\BackEnd\4.5 Capstone Prject To-Do-List\node_modules\ejs\lib\ejs.js:673:12), :12:26)
at index (C:\Users\Niklaus\Desktop\Web Develepment Course\BackEnd\4.5 Capstone Prject To-Do-List\node_modules\ejs\lib\ejs.js:703:17)
at tryHandleCache (C:\Users\Niklaus\Desktop\Web Develepment Course\BackEnd\4.5 Capstone Prject To-Do-List\node_modules\ejs\lib\ejs.js:274:36)
at exports.renderFile [as engine] (C:\Users\Niklaus\Desktop\Web Develepment Course\BackEnd\4.5 Capstone Prject To-Do-List\node_modules\ejs\lib\ejs.js:491:10)
at View.render (C:\Users\Niklaus\Desktop\Web Develepment Course\BackEnd\4.5 Capstone Prject To-Do-List\node_modules\express\lib\view.js:135:8)
at tryRender (C:\Users\Niklaus\Desktop\Web Develepment Course\BackEnd\4.5 Capstone Prject To-Do-List\node_modules\express\lib\application.js:657:10)
at Function.render (C:\Users\Niklaus\Desktop\Web Develepment Course\BackEnd\4.5 Capstone Prject To-Do-List\node_modules\express\lib\application.js:609:3)
at ServerResponse.render (C:\Users\Niklaus\Desktop\Web Develepment Course\BackEnd\4.5 Capstone Prject To-Do-List\node_modules\express\lib\response.js:1039:7)
at file:///C:/Users/Niklaus/Desktop/Web%20Develepment%20Course/BackEnd/4.5%20Capstone%20Prject%20To-Do-List/index.js:19:9
at Layer.handle [as handle_request] (C:\Users\Niklaus\Desktop\Web Develepment Course\BackEnd\4.5 Capstone Prject To-Do-List\node_modules\express\lib\router\layer.js:95:5) 英文:
ESJ Code : {#esj-code-}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>To-Do-List</title>
<link rel="stylesheet" href="public\styles.css" />
<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-4bw+/aepP/YC94hEpVNVgiZdgIC5+VKNBQNGCHeKRQN+PtmoHDEXuppvnDJzQIu9"
crossorigin="anonymous"
/>
<script
src="https://kit.fontawesome.com/20accab6ba.js"
crossorigin="anonymous"
></script>
</head>
<body>
<div
class="d-flex flex-column flex-md-row p-4 gap-4 py-md-5 align-items-center justify-content-center"
>
<div class="list-group">
<form
class="list-group-item d-flex gap-3 bg-body-tertiary"
action="/submit"
method="POST"
>
<span class="pt-1 form-checked-content">
<span contenteditable="true" class="w-100" id="taskInput">
<input
type="text"
id="task"
name="task"
placeholder="Enter your task"
/>
</span>
<small class="d-block text-body-secondary">
<i
class="fa-regular fa-clock bi me-1"
width="1em"
height="1em"
style="color: #7a8290"
></i>
<input type="time" id="time" name="time" />
</small>
</span>
<%= variable %>
<button class="btn btn-primary" type="submit">Submit</button>
</form>
</div>
</div>
</body>
</html>
I have Tried it Everthing works fine but it does not work when I use something on EJS.
I can't Find any solution
Server Code: {#server-code}
import express from "express";
import bodyParser from 'body-parser';
import ejs from "ejs";
import { dirname } from "path";
import { fileURLToPath } from "url";
const app = express();
const port = 3000;
const __dirname = dirname(fileURLToPath(import.meta.url));
const currentTime = new Date();
const hours = currentTime.getHours();
const minutes = currentTime.getMinutes();
app.use(express.static("public"));
app.use(bodyParser.urlencoded({ extended: true }));
app.get("/", (req,res) =>{
res.render(`${__dirname}/views/index.ejs`);
});
app.post('/submit', (req, res) => {
res.render(`${__dirname}/views/index.ejs`,
{
variable : "Hi",
})
});
app.listen(port, () => {
console.log("Sever started at port:" + port);
});
Error: {#error}
> ReferenceError: C:\Users\Niklaus\Desktop\Web Develepment Course\BackEnd\4.5 Capstone Prject To-Do-List\views\index.ejs:26
> 24| </small>
>
> 25| </span>
>
> 26| <%= variable %>
>
> 27|
>
> 28| <button class="btn btn-primary" type="submit">Submit</button>
>
> 29| </form>
>
>
> variable is not defined
> at eval (eval at compile (C:\Users\Niklaus\Desktop\Web Develepment Course\BackEnd\4.5 Capstone Prject To-Do-List\node_modules\ejs\lib\ejs.js:673:12), <anonymous>:12:26)
> at index (C:\Users\Niklaus\Desktop\Web Develepment Course\BackEnd\4.5 Capstone Prject To-Do-List\node_modules\ejs\lib\ejs.js:703:17)
> at tryHandleCache (C:\Users\Niklaus\Desktop\Web Develepment Course\BackEnd\4.5 Capstone Prject To-Do-List\node_modules\ejs\lib\ejs.js:274:36)
> at exports.renderFile [as engine] (C:\Users\Niklaus\Desktop\Web Develepment Course\BackEnd\4.5 Capstone Prject To-Do-List\node_modules\ejs\lib\ejs.js:491:10)
> at View.render (C:\Users\Niklaus\Desktop\Web Develepment Course\BackEnd\4.5 Capstone Prject To-Do-List\node_modules\express\lib\view.js:135:8)
> at tryRender (C:\Users\Niklaus\Desktop\Web Develepment Course\BackEnd\4.5 Capstone Prject To-Do-List\node_modules\express\lib\application.js:657:10)
> at Function.render (C:\Users\Niklaus\Desktop\Web Develepment Course\BackEnd\4.5 Capstone Prject To-Do-List\node_modules\express\lib\application.js:609:3)
> at ServerResponse.render (C:\Users\Niklaus\Desktop\Web Develepment Course\BackEnd\4.5 Capstone Prject To-Do-List\node_modules\express\lib\response.js:1039:7)
> at file:///C:/Users/Niklaus/Desktop/Web%20Develepment%20Course/BackEnd/4.5%20Capstone%20Prject%20To-Do-List/index.js:19:9
> at Layer.handle [as handle_request] (C:\Users\Niklaus\Desktop\Web Develepment Course\BackEnd\4.5 Capstone Prject To-Do-List\node_modules\express\lib\router\layer.js:95:5)
答案1 {#1}
得分: 0
-
在后端代码中,我认为存在一些错误,
-
变量未被正确传递或未在渲染代码的范围内定义。
app.set('view engine', 'ejs'); app.get("/", (req, res) => { res.render('${__dirname}/views/index.ejs', { variable: "" }); }); app.post('/submit', (req, res) => { const variableValue = "Hi"; res.render('${__dirname}/views/index.ejs', { variable: variableValue }); });
问题出在变量从上面传递的地方,现在应该可以正常工作了。
英文:
I think there are few errors in Backend code ,
-
Setting the view engine
-
variable is not being passed correctly or is not defined in the scope of your rendering code.
app.set('view engine', 'ejs');
app.get("/", (req, res) => {
res.render('${__dirname}/views/index.ejs', { variable: "" });
});
app.post('/submit', (req, res) => {
const variableValue = "Hi";
res.render('${__dirname}/views/index.ejs', { variable: variableValue });
});
The issue was with passing the Variable from up , this should work now .
答案2 {#2}
得分: 0
首先,如果你正在使用ejs,你应该设置视图引擎以便使用ejs:
app.set("view engine", "ejs");
现在,你可以使用以下方式渲染你的文档,使用你的文件名:
app.get("/", (req, res) => {
res.render("index");
});
但这与你的问题无关。你的问题是尝试在没有变量的情况下渲染你的index.ejs文件。当你尝试访问"/"路径时,index.ejs文件正在提供服务,但你没有声明变量,所以ejs会报错。你应该在你的ejs文件中添加一个if语句:
....
<% if (locals.variable) { %> // is variable undefined on local variables ?
<%= variable %>
<% } %>
<button class="btn btn-primary" type="submit">Submit</button>
....
或者创建一个新文件来服务"/submit"路径。 英文:
First of all if you're using ejs you should set view engine to serve ejs with:
app.set("view engine", "ejs");
now you can render your document with your file's name. with :
app.get("/", (req,res) =>{
res.render("index");
});
But it's not related with your problem. Your problem is you are trying to render your index.ejs file without a variable. When you try to access on "/" path your index.ejs file is serving but you didn't declare it so ejs gives error. You should add a if statement on your ejs.
....
<% if (locals.variable) { %> // is variable undefined on local variables ?
<%= variable %>
<% } %>
<button class="btn btn-primary" type="submit">Submit</button>
....
or create a new file to serve "/submit" path