【问题标题】:Send array from async function node js to html将数组从异步函数节点 js 发送到 html
【发布时间】:2022-01-03 22:34:05
【问题描述】:

我正在尝试将一个 js 数组从我的节点 js 后端发送到我的 html,但 HTML 中的对象是一个 Promise 对象,我怎样才能正确发送该数组?

我收到此错误 =

Uncaught SyntaxError: Unexpected identifier

console.log([object Promise]);

后端:

 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 server = express();
server.use(express.static(path.join(__dirname, 'public')));
server.use(express.static(path.join(__dirname + '/js')));//middleware
server.use(express(__dirname)); 
server.set('view engine','html');
server.engine('html', require('ejs').renderFile);

server.get("*", function(request, response){ 
 response.render('index.html', {obj: productArr});
});
const Shopify = require('shopify-api-node');

const shopify = new Shopify({
  shopName: 'this.myshopify.com',
  apiKey: 'apikey',
  password: 'pass'
});

async function getJson() {
 return shopify.product.list();
}

let productArr = getJson();
//console.log(productArr);

server.listen(port, host);
console.log('Running at Port 1337');

前端

<script>
   console.log(<%= obj %>);
</script>

【问题讨论】:

    标签: javascript html node.js arrays


    【解决方案1】:

    使用异步函数并等待承诺:

    server.get("*", async function(request, response){ 
     response.render('index.html', {obj: await productArr});
    });
    

    有关async functionspromises 的更多信息。

    同样在您的index.html 中,您需要将对象转换为字符串并将&lt;%= 更改为&lt;%-(不会转义文本):

    <script>
       console.log(<%- JSON.stringify(obj) %>);
    </script>
    

    更多关于JSON stringifyejs的信息

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-22
      • 2018-10-09
      • 2020-07-06
      • 1970-01-01
      • 2016-11-25
      • 2013-06-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多