How can I send my json to my view with node js

2019-09-13 06:16发布

问题:

I have a previous question about this so take a look here.

I can now login to spotify and get the playlists of the user that is loged in. I now want to send these playlists (they are in json) to a view of to an html page or ...

This is what my code looks like:

app.get('/playlists', function(req, res) {
  var state = generateRandomString(16);
  res.cookie(stateKey, state);
  var scope = 'playlist-read-private';
  var options = {
    url:"https://api.spotify.com/v1/me/playlists",
    headers:{
      'Authorization': "Bearer " + token,
      'response_type': 'code',
      'client_id': client_id,
      'scope': scope,
      'state': state
    },
    json:true
  };
  request.get(options, function(error, req, body){
    console.log(body);
    //Here I want to send the json to the view
    res.send(body);
  });
});

The problem with this code "res.send(body);" is that I get this as url: localhost:8888/playlists and in this page I just see the json. I would like to send it to a view where I can chose what info I show. Can someone help me with this?

Thanks in advance

回答1:

In that case, you can use an ajax request to the server with a library of your choice, and when you receive the data after the ajax, you update your view using the data. With jQuery you might do something like:

var jqxhr = $.get('/playlist', {parameters});
jqxhr.done(function(data){
//data is your json response you can manipulate.
});

You might also want to use res.json() witch is more appropriate to send json responses in express.



回答2:

If you want to send a JSON you can do this

  return res.status(200).json({ "text": "Hello World!" });