简体   繁体   English

在 express 和 ejs 模板中使用 fetch 添加脚本以通过客户端从第 3 方获取数据

[英]Add a script using fetch to get data by client side from a 3rd party, in express and ejs templating

My express app is using ejs as template to render html to the client.我的 Express 应用程序使用 ejs 作为模板向客户端呈现 html。

I'm trying to make the client send a http get request to a 3rd party api, using the native "fetch" method.我试图让客户端使用本机“获取”方法向第三方 api 发送 http get 请求。 but the client must use data from my app for the request.但客户端必须使用我的应用程序中的数据来满足请求。

Now if i'm putting in the function inside the ejs <%%> tag i'm getting A error in the browser "fetch is not defined".现在,如果我将 function 放入 ejs <%%> 标记内,我会在浏览器中收到错误消息“未定义获取”。

Have a look on my code please.请看看我的代码。

The code in my ejs file我的 ejs 文件中的代码

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

And in my app.js在我的 app.js 中

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

You don't need an entire EJS scriplet.您不需要完整的EJS 脚本。 Just use a <script> tag and output the EJS variables when necessary.必要时只需使用<script>标记和 output EJS 变量。 I also see you are not outputting your variables you inputted in your app.js , you must do this to use the variables you are passing in.我还看到您没有输出您在app.js中输入的变量,您必须这样做才能使用您传入的变量。

Example:例子:

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

The EJS documentation covering a lot of useful information can be found here.可以在此处找到包含大量有用信息的 EJS 文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM