【问题标题】:JSON Request in body html正文 html 中的 JSON 请求
【发布时间】:2017-07-10 05:07:14
【问题描述】:

我正在尝试向 API 服务器发出 https.request。我可以接收块(JSON)并在控制台中打印它。怎么直接写成html在浏览器中显示?

var requestListener = function (req, res) {

    var db = admin.database(); 
    var ref = db.ref("Clubs"); 
    ref.on("value", function(snapshot) { 

   console.log(snapshot.val());     //print on console

       res.write( snapshot.val() ); // in body html, error       throw er;                               
       // Unhandled 'error' event ^Error: write after end

    }, function (errorObject) {         
        console.log("The read failed: " + errorObject.code);

    });

// CRUD

    ref.child("club1").set({
        clubId: 1,
        clubName: "club1",
        telephone: "6548798",
        address: "Lviv",
        party: "qwe,asd,zxc"
    });

    ref.child("club2").set({
        clubId: 2,
        clubName: "club2",
        telephone: "234234",
        address: "Kiev",
        party: "qwe,zxc"
    });    
    res.end();
};

var server = http.createServer(requestListener);
server.listen(8080);

【问题讨论】:

  • 你必须对 JSON 进行字符串化

标签: javascript json node.js firebase firebase-realtime-database


【解决方案1】:

您在requestListener 的末尾调用res.end()。但它是在“定义”数据库读取处理程序之后调用的。因此,当您的数据库第一次触发 'value' 事件时,发送 HTTP 响应数据为时已晚。

要修复它,您需要将res.end(); 移动到数据库完成推送其数据的位置。应该有一个closeend 事件,具体取决于您使用的数据库/适配器。如果不是,那么正确的位置应该是在.write() 之后,如果这可以保证是一次只调用'value' 事件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-06
    • 2019-01-24
    • 2013-05-30
    • 2022-11-17
    • 2015-03-20
    • 2018-09-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多