Node.js中async函数返回的数组如何正确传递到HTML页面
问题根因
- 异步函数
getJson调用后返回的是Promise对象而非实际的商品数组,你直接将未resolve的Promise传入模板,前端自然只能拿到[object Promise]的字符串结果 - EJS的
<%= %>标签默认会对输出内容做HTML转义,就算传入了真实数组,直接输出到script标签内也会生成非法JS语法,触发Unexpected identifier报错
修复方案
后端代码修改
首先调整路由逻辑,在请求处理时等待异步接口返回真实数据后再渲染模板,同时修正无效的中间件配置:
const path = require('path'); const fs = require("fs"); const host = "127.0.0.1"; const port = 1337; const express = require("express"); const ejs = require("ejs"); const Shopify = require('shopify-api-node'); const server = express(); server.use(express.static(path.join(__dirname, 'public'))); server.use(express.static(path.join(__dirname, '/js'))); // 修正原错误的中间件写法,原express(__dirname)是无效配置 server.use(express.static(__dirname)); server.set('view engine','html'); server.engine('html', require('ejs').renderFile); const shopify = new Shopify({ shopName: 'this.myshopify.com', apiKey: 'apikey', password: 'pass' }); async function getJson() { return shopify.product.list(); } // 将路由处理函数改为异步,等待接口返回后再渲染 server.get("*", async function(request, response){ const productArr = await getJson(); response.render('index.html', {obj: productArr}); }); server.listen(port, host); console.log('Running at Port 1337');
如果你需要全局只请求一次Shopify接口缓存数据,也可以等待接口返回后再启动服务:
// 省略其余相同代码 let productArr; async function init() { productArr = await getJson(); server.listen(port, host); console.log('Running at Port 1337'); } init();
前端模板修改
改用不转义的EJS标签<%- %>,同时将数组序列化为JSON字符串,保证输出到script标签内是合法的JS语法:
<script> console.log(<%- JSON.stringify(obj) %>); </script>
内容的提问来源于stack exchange,提问作者Rafael G
相关产品推荐
相关产品推荐

