Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send json data from node js to html page

Tags:

node.js

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.

like image 979
Jianyuan Ma Avatar asked Jun 28 '13 12:06

Jianyuan Ma


People also ask

How fetch data from JSON to HTML?

The jQuery code uses getJSON() method to fetch the data from the file's location using an AJAX HTTP GET request. It takes two arguments. One is the location of the JSON file and the other is the function containing the JSON data. The each() function is used to iterate through all the objects in the array.

How do you send HTML and JSON a response in node JS?

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 $.


1 Answers

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.

like image 66
moka Avatar answered Oct 17 '22 01:10

moka