【问题标题】:Add a script using fetch to get data by client side from a 3rd party, in express and ejs templating在 express 和 ejs 模板中,使用 fetch 添加脚本以通过客户端从第 3 方获取数据
【发布时间】:2021-10-25 12:48:18
【问题描述】:

我的 express 应用使用 ejs 作为模板向客户端呈现 html。

我正在尝试让客户端使用本机“获取”方法向第 3 方 api 发送一个 http get 请求。但是客户端必须使用我的应用程序中的数据进行请求。

现在,如果我将函数放入 ejs 标记中,我会在浏览器中收到错误“未定义提取”。

请看一下我的代码。

我的 ejs 文件中的代码

<%fetch("url"+name[0]).then(response => response.json()).then(%><%=response%><%)%>

在我的 app.js 中

res.render("index",{name:["jon","donald","jo"]})

【问题讨论】:

    标签: javascript express fetch ejs


    【解决方案1】:

    您不需要整个EJS scriplet. 只需使用&lt;script&gt; 标记并在必要时输出EJS 变量。我还看到您没有输出您在app.js 中输入的变量,您必须这样做才能使用您传入的变量。

    例子:

    <script>
       fetch("url<%= name[0] %>").then(response => response.json());
    </script>
    

    涵盖很多有用信息的EJS文档可以在here.找到

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-19
      • 2017-03-06
      • 1970-01-01
      • 2022-01-21
      • 2017-11-06
      • 2020-08-01
      • 1970-01-01
      • 2023-03-10
      相关资源
      最近更新 更多