node.js 如何将json数据从节点js发送到html页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17365039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:54:43  来源:igfitidea点击:

How to send json data from node js to html page

node.js

提问by Jianyuan Ma

I have already get a serier of json data from facebook using node js express. Now I want to send the data to a html page. But I have no idea how to send the data and encode the data in html.

我已经使用 node js express 从 Facebook 获得了一系列 json 数据。现在我想将数据发送到 html 页面。但我不知道如何发送数据并将数据编码为 html。

回答by moka

If you use Express in node.js, here is the way to send json object as response:

如果你在 node.js 中使用 Express,这里是发送 json 对象作为响应的方式:

app.get('/test', function(req, res, next) {
  res.json({ message: 'Hello World' });
});

Then in JS on your html page html, if you use jQuery:

然后在您的 html 页面 html 上的 JS 中,如果您使用 jQuery:

$.ajax({
  url: '/test',
  complete: function(data) {
    console.log(data);
  }
});

Feel free to experiment with stuff, as well use Dev Tools in Chrome, experimentation - helps a lot to understand what and how it works.

随意尝试一些东西,以及在 Chrome 中使用开发工具,实验 - 对理解它的工作原理和方式有很大帮助。

回答by slobodan.blazeski

Something like function(req,res) { res.json({ user: 'tobi' }) } http://expressjs.com/api.html#res.json

类似于 function(req,res) { res.json({ user: 'tobi' }) } http://expressjs.com/api.html#res.json

回答by Digi49

Check out Heroku's example tutorial. I think it does exactly what you are asking for in terms of JSON encoding + throws in Web Sockets. https://devcenter.heroku.com/articles/node-websockets

查看 Heroku 的示例教程。我认为它完全符合您在 JSON 编码 + Web 套接字中抛出的要求。https://devcenter.heroku.com/articles/node-websockets