【问题标题】:Send back data from node.js to client side javascript将数据从 node.js 发送回客户端 javascript
【发布时间】:2019-07-21 19:22:52
【问题描述】:

我想要做的是以下我已经设置了一个从客户端 JS 到服务器 Node.JS 的获取连接,当一个人点击 HTML 中的一个按钮时,触发服务器端在服务器端寻找一个元素它找到了 MongoDB 数据库,但我的问题是如何将找到的元素发送回客户端 JS。

Javascript Code:

var button = document.getElementById("1");

button.addEventListener("click", idss);


function idss() {
      var id = this.id;

    var data = {
    name : id 
}

fetch("/clicked", {
     method: 'POST',
     headers: {
     'Content-Type': 'application/json'
     }, 
     body: JSON.stringify(data)
})
   .then(function(response) {
      if(response.ok) {
        console.log('awesome');
        return;
      }
      throw new Error('Request failed.');
    })
    .catch(function(error) {
      console.log(error);
    }); 
}


NODE JS:

app.post("/clicked", (req, res) => {
    var pro = (req.body.name);
    Number(pro);
    Product.findOne({"id": pro}, function(err, foundLList) {
        if(err) {
            console.log(err);
        } else {
            console.log(foundLList); //THE ELEMENT IS FOUND
        }
    } 
  ); 
});

我想要做的是将找到的元素发送到 Javascript,以便我可以添加到另一个变量。

【问题讨论】:

  • 在 Node.js 中使用 res.send(data);实际返回一些东西。据我所知,大部分 MongoDB 函数都是异步的,所以最好使用 async/await
  • 您正在使用 Express.js,这在文档开头的基本 Hello World 示例中有所介绍。

标签: javascript node.js express


【解决方案1】:

您必须使用 res 对象将数据发送回客户端。您的节点代码将是:

app.post("/clicked", (req, res) => {
    var pro = (req.body.name);
    Number(pro);
    Product.findOne({
        "id": pro
    }, function(err, foundLList) {
        if (err) {
            console.log(err);
            return res.status(500).json({
                ok: false,
                error: err
            });
        } else {
            console.log(foundLList); //THE ELEMENT IS FOUND
            return res.status(200).json({
                ok: true,
                data: foundLList
            });

        }
    });
});

在客户端,您可以像这样读取数据:

fetch("/clicked", {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(function(response) {
        if (response.ok) {
            console.log('got data: ', response.data);
        }
        throw new Error('Request failed.');
    })
    .catch(function(error) {
        console.log(error);
    });
}

【讨论】:

  • 我尝试在 response.data 的未定义中放入未定义。
  • 尝试将响应对象转换为 JSON。在我们之前添加.then(response => response.json())
  • Thaks Mohammed 我用这段代码解决了它 .then(response => response.json()) .then(res => { if(res.ok) { console.log(res); }
  • 很高兴有帮助:)
猜你喜欢
  • 2022-01-09
  • 1970-01-01
  • 2013-02-01
  • 2017-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多