在 express 和 ejs 模板中使用 fetch 添加脚本以通过客户端从第 3 方获取数据
Add a script using fetch to get data by client side from a 3rd party, in express and ejs templating
我的 Express 应用使用 ejs 作为模板向客户端呈现 html。
我正在尝试让客户端使用本机“获取”方法向第三方 api 发送 http get 请求。但客户端必须使用我的应用程序中的数据来请求。
现在,如果我将函数放入 ejs <%%> 标记内,我会在浏览器中收到错误消息“未定义获取”。
请看一下我的代码。
我的ejs文件中的代码
<%fetch("url"+name[0]).then(response => response.json()).then(%><%=response%><%)%>
在我的 app.js
res.render("index",{name:["jon","donald","jo"]})
您不需要整个 EJS scriplet. 只需使用 <script>
标记并在必要时输出 EJS 变量。我还看到您没有输出您在 app.js
中输入的变量,您必须这样做才能使用您传入的变量。
示例:
<script>
fetch("url<%= name[0] %>").then(response => response.json());
</script>
可以找到包含大量有用信息的 EJS 文档 here.
我的 Express 应用使用 ejs 作为模板向客户端呈现 html。
我正在尝试让客户端使用本机“获取”方法向第三方 api 发送 http get 请求。但客户端必须使用我的应用程序中的数据来请求。
现在,如果我将函数放入 ejs <%%> 标记内,我会在浏览器中收到错误消息“未定义获取”。
请看一下我的代码。
我的ejs文件中的代码
<%fetch("url"+name[0]).then(response => response.json()).then(%><%=response%><%)%>
在我的 app.js
res.render("index",{name:["jon","donald","jo"]})
您不需要整个 EJS scriplet. 只需使用 <script>
标记并在必要时输出 EJS 变量。我还看到您没有输出您在 app.js
中输入的变量,您必须这样做才能使用您传入的变量。
示例:
<script>
fetch("url<%= name[0] %>").then(response => response.json());
</script>
可以找到包含大量有用信息的 EJS 文档 here.