Jianyuan Ma
Jianyuan Ma

Reputation: 325

How to send json data from node js to html page

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.

Upvotes: 10

Views: 30838

Answers (3)

slobodan.blazeski
slobodan.blazeski

Reputation: 1040

Use res.json. For instance:

function(req,res) {
  res.json({ user: 'tobi' })
}

Upvotes: 0

Digi49
Digi49

Reputation: 1

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

Upvotes: 0

moka
moka

Reputation: 23047

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

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

Then in JS on your html page html, if you use 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.

Upvotes: 20

Related Questions