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

我与影子孤独终老i 提交于 2019-12-12 03:42:43

问题


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!" });


来源:https://stackoverflow.com/questions/40659653/how-can-i-send-my-json-to-my-view-with-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!