EJS在我使用从服务器传递的变量时不起作用。

huangapple go评论105阅读模式
英文:

EJS is not working when I use a variable that is passed from server

问题

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>

服务器代码:

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);
});

错误:

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 :

&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
&lt;meta charset=&quot;UTF-8&quot; /&gt;
&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt;
&lt;title&gt;To-Do-List&lt;/title&gt;
&lt;link rel=&quot;stylesheet&quot; href=&quot;public\styles.css&quot; /&gt;
&lt;link
href=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/css/bootstrap.min.css&quot;
rel=&quot;stylesheet&quot;
integrity=&quot;sha384-4bw+/aepP/YC94hEpVNVgiZdgIC5+VKNBQNGCHeKRQN+PtmoHDEXuppvnDJzQIu9&quot;
crossorigin=&quot;anonymous&quot;
/&gt;
&lt;script
src=&quot;https://kit.fontawesome.com/20accab6ba.js&quot;
crossorigin=&quot;anonymous&quot;
&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;div
class=&quot;d-flex flex-column flex-md-row p-4 gap-4 py-md-5 align-items-center justify-content-center&quot;
&gt;
&lt;div class=&quot;list-group&quot;&gt;
&lt;form
class=&quot;list-group-item d-flex gap-3 bg-body-tertiary&quot;
action=&quot;/submit&quot;
method=&quot;POST&quot;
&gt;
&lt;span class=&quot;pt-1 form-checked-content&quot;&gt;
&lt;span contenteditable=&quot;true&quot; class=&quot;w-100&quot; id=&quot;taskInput&quot;&gt;
&lt;input
type=&quot;text&quot;
id=&quot;task&quot;
name=&quot;task&quot;
placeholder=&quot;Enter your task&quot;
/&gt;
&lt;/span&gt;
&lt;small class=&quot;d-block text-body-secondary&quot;&gt;
&lt;i
class=&quot;fa-regular fa-clock bi me-1&quot;
width=&quot;1em&quot;
height=&quot;1em&quot;
style=&quot;color: #7a8290&quot;
&gt;&lt;/i&gt;
&lt;input type=&quot;time&quot; id=&quot;time&quot; name=&quot;time&quot; /&gt;
&lt;/small&gt;
&lt;/span&gt;
&lt;%= variable %&gt;
&lt;button class=&quot;btn btn-primary&quot; type=&quot;submit&quot;&gt;Submit&lt;/button&gt;
&lt;/form&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;

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:

import express from &quot;express&quot;;
import bodyParser from &#39;body-parser&#39;;
import ejs from &quot;ejs&quot;;
import { dirname } from &quot;path&quot;;
import { fileURLToPath } from &quot;url&quot;;
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(&quot;public&quot;));
app.use(bodyParser.urlencoded({ extended: true }));
app.get(&quot;/&quot;, (req,res) =&gt;{
res.render(`${__dirname}/views/index.ejs`);
});
app.post(&#39;/submit&#39;, (req, res) =&gt; {
res.render(`${__dirname}/views/index.ejs`, 
{
variable : &quot;Hi&quot;,
})  
});
app.listen(port, () =&gt; {
console.log(&quot;Sever started at port:&quot; + port);
});

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

得分: 0

  1. 在后端代码中,我认为存在一些错误,

  2. 变量未被正确传递或未在渲染代码的范围内定义。

    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 ,

  1. Setting the view engine

  2. variable is not being passed correctly or is not defined in the scope of your rendering code.

    app.set(&#39;view engine&#39;, &#39;ejs&#39;);
    app.get(&quot;/&quot;, (req, res) =&gt; {
    res.render(&#39;${__dirname}/views/index.ejs&#39;, { variable: &quot;&quot; });
    });

    app.post(&#39;/submit&#39;, (req, res) =&gt; {
    const variableValue = &quot;Hi&quot;;
    res.render(&#39;${__dirname}/views/index.ejs&#39;, { variable: variableValue });
    });

The issue was with passing the Variable from up , this should work now .

答案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(&quot;view engine&quot;, &quot;ejs&quot;);

now you can render your document with your file's name. with :

app.get(&quot;/&quot;, (req,res) =&gt;{
res.render(&quot;index&quot;);
});

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.

....
&lt;% if (locals.variable) { %&gt; // is variable undefined on local variables ? 
&lt;%= variable %&gt;
&lt;% } %&gt;
&lt;button class=&quot;btn btn-primary&quot; type=&quot;submit&quot;&gt;Submit&lt;/button&gt;
....

or create a new file to serve "/submit" path

huangapple
  • 本文由 发表于 2023年8月10日 21:39:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76876284.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定