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

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

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

问题

ESJ 代码:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  6. <title>待办事项列表</title>
  7. <link rel="stylesheet" href="public\styles.css" />
  8. <link
  9. href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/css/bootstrap.min.css"
  10. rel="stylesheet"
  11. integrity="sha384-4bw+/aepP/YC94hEpVNVgiZdgIC5+VKNBQNGCHeKRQN+PtmoHDEXuppvnDJzQIu9"
  12. crossorigin="anonymous"
  13. />
  14. <script
  15. src="https://kit.fontawesome.com/20accab6ba.js"
  16. crossorigin="anonymous"
  17. ></script>
  18. </head>
  19. <body>
  20. <div
  21. class="d-flex flex-column flex-md-row p-4 gap-4 py-md-5 align-items-center justify-content-center"
  22. >
  23. <div class="list-group">
  24. <form
  25. class="list-group-item d-flex gap-3 bg-body-tertiary"
  26. action="/submit"
  27. method="POST"
  28. >
  29. <span class="pt-1 form-checked-content">
  30. <span contenteditable="true" class="w-100" id="taskInput">
  31. <input
  32. type="text"
  33. id="task"
  34. name="task"
  35. placeholder="输入您的任务"
  36. />
  37. </span>
  38. <small class="d-block text-body-secondary">
  39. <i
  40. class="fa-regular fa-clock bi me-1"
  41. width="1em"
  42. height="1em"
  43. style="color: #7a8290"
  44. ></i>
  45. <input type="time" id="time" name="time" />
  46. </small>
  47. </span>
  48. <%= variable %>
  49. <button class="btn btn-primary" type="submit">提交</button>
  50. </form>
  51. </div>
  52. </div>
  53. </body>
  54. </html>

服务器代码:

  1. import express from "express";
  2. import bodyParser from 'body-parser';
  3. import ejs from "ejs";
  4. import { dirname } from "path";
  5. import { fileURLToPath } from "url";
  6. const app = express();
  7. const port = 3000;
  8. const __dirname = dirname(fileURLToPath(import.meta.url));
  9. const currentTime = new Date();
  10. const hours = currentTime.getHours();
  11. const minutes = currentTime.getMinutes();
  12. app.use(express.static("public"));
  13. app.use(bodyParser.urlencoded({ extended: true }));
  14. app.get("/", (req, res) => {
  15. res.render(`${__dirname}/views/index.ejs`);
  16. });
  17. app.post('/submit', (req, res) => {
  18. res.render(`${__dirname}/views/index.ejs`, {
  19. variable: "你好",
  20. });
  21. });
  22. app.listen(port, () => {
  23. console.log("服务器已启动,端口:" + port);
  24. });

错误:

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 :

  1. &lt;!DOCTYPE html&gt;
  2. &lt;html lang=&quot;en&quot;&gt;
  3. &lt;head&gt;
  4. &lt;meta charset=&quot;UTF-8&quot; /&gt;
  5. &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt;
  6. &lt;title&gt;To-Do-List&lt;/title&gt;
  7. &lt;link rel=&quot;stylesheet&quot; href=&quot;public\styles.css&quot; /&gt;
  8. &lt;link
  9. href=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/css/bootstrap.min.css&quot;
  10. rel=&quot;stylesheet&quot;
  11. integrity=&quot;sha384-4bw+/aepP/YC94hEpVNVgiZdgIC5+VKNBQNGCHeKRQN+PtmoHDEXuppvnDJzQIu9&quot;
  12. crossorigin=&quot;anonymous&quot;
  13. /&gt;
  14. &lt;script
  15. src=&quot;https://kit.fontawesome.com/20accab6ba.js&quot;
  16. crossorigin=&quot;anonymous&quot;
  17. &gt;&lt;/script&gt;
  18. &lt;/head&gt;
  19. &lt;body&gt;
  20. &lt;div
  21. class=&quot;d-flex flex-column flex-md-row p-4 gap-4 py-md-5 align-items-center justify-content-center&quot;
  22. &gt;
  23. &lt;div class=&quot;list-group&quot;&gt;
  24. &lt;form
  25. class=&quot;list-group-item d-flex gap-3 bg-body-tertiary&quot;
  26. action=&quot;/submit&quot;
  27. method=&quot;POST&quot;
  28. &gt;
  29. &lt;span class=&quot;pt-1 form-checked-content&quot;&gt;
  30. &lt;span contenteditable=&quot;true&quot; class=&quot;w-100&quot; id=&quot;taskInput&quot;&gt;
  31. &lt;input
  32. type=&quot;text&quot;
  33. id=&quot;task&quot;
  34. name=&quot;task&quot;
  35. placeholder=&quot;Enter your task&quot;
  36. /&gt;
  37. &lt;/span&gt;
  38. &lt;small class=&quot;d-block text-body-secondary&quot;&gt;
  39. &lt;i
  40. class=&quot;fa-regular fa-clock bi me-1&quot;
  41. width=&quot;1em&quot;
  42. height=&quot;1em&quot;
  43. style=&quot;color: #7a8290&quot;
  44. &gt;&lt;/i&gt;
  45. &lt;input type=&quot;time&quot; id=&quot;time&quot; name=&quot;time&quot; /&gt;
  46. &lt;/small&gt;
  47. &lt;/span&gt;
  48. &lt;%= variable %&gt;
  49. &lt;button class=&quot;btn btn-primary&quot; type=&quot;submit&quot;&gt;Submit&lt;/button&gt;
  50. &lt;/form&gt;
  51. &lt;/div&gt;
  52. &lt;/div&gt;
  53. &lt;/body&gt;
  54. &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:

  1. import express from &quot;express&quot;;
  2. import bodyParser from &#39;body-parser&#39;;
  3. import ejs from &quot;ejs&quot;;
  4. import { dirname } from &quot;path&quot;;
  5. import { fileURLToPath } from &quot;url&quot;;
  6. const app = express();
  7. const port = 3000;
  8. const __dirname = dirname(fileURLToPath(import.meta.url));
  9. const currentTime = new Date();
  10. const hours = currentTime.getHours();
  11. const minutes = currentTime.getMinutes();
  12. app.use(express.static(&quot;public&quot;));
  13. app.use(bodyParser.urlencoded({ extended: true }));
  14. app.get(&quot;/&quot;, (req,res) =&gt;{
  15. res.render(`${__dirname}/views/index.ejs`);
  16. });
  17. app.post(&#39;/submit&#39;, (req, res) =&gt; {
  18. res.render(`${__dirname}/views/index.ejs`,
  19. {
  20. variable : &quot;Hi&quot;,
  21. })
  22. });
  23. app.listen(port, () =&gt; {
  24. console.log(&quot;Sever started at port:&quot; + port);
  25. });

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. 变量未被正确传递或未在渲染代码的范围内定义。

    1. app.set('view engine', 'ejs');
    2. app.get("/", (req, res) => {
    3. res.render('${__dirname}/views/index.ejs', { variable: "" });
    4. });
    5. app.post('/submit', (req, res) => {
    6. const variableValue = "Hi";
    7. res.render('${__dirname}/views/index.ejs', { variable: variableValue });
    8. });

    问题出在变量从上面传递的地方,现在应该可以正常工作了。

英文:

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:

  1. app.set("view engine", "ejs");

现在,你可以使用以下方式渲染你的文档,使用你的文件名:

  1. app.get("/", (req, res) => {
  2. res.render("index");
  3. });

但这与你的问题无关。你的问题是尝试在没有变量的情况下渲染你的index.ejs文件。当你尝试访问"/"路径时,index.ejs文件正在提供服务,但你没有声明变量,所以ejs会报错。你应该在你的ejs文件中添加一个if语句:

  1. ....
  2. <% if (locals.variable) { %> // is variable undefined on local variables ?
  3. <%= variable %>
  4. <% } %>
  5. <button class="btn btn-primary" type="submit">Submit</button>
  6. ....

或者创建一个新文件来服务"/submit"路径。

英文:

First of all if you're using ejs you should set view engine to serve ejs with:

  1. app.set(&quot;view engine&quot;, &quot;ejs&quot;);

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

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

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.

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

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:

确定