10

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.

3 Answers 3

20

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.

Sign up to request clarification or add additional context in comments.

5 Comments

TIL res.json() - that's just saved me a load of effort with JSON.stringify all over the place
You could do res.send() as well, as far as I am concern, latest express will add application/json Content-Type if you try to send object. It is up to jQuery to parse it properly. Although if Content-Type is not json but you still sure it will be always json, then you can force it in jQuery by adding dataType: 'json' in parameters in $.ajax({ ..
Interesting, thanks for the info (although admittedly I feel like I should've just read the docs and saved you the time ;))
@JianyuanMa you are welcome. Please use accept features and rating system of StackOverflow, read this: stackoverflow.com/about
Finally, this is what I was looking for ... well working
0

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

1 Comment

It is better to give a brief explanation, and provide the link for reference of details. Link-only answers may become invalid if the linked page changes.
0

Use res.json. For instance:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.