Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

npm request not getting json response when doing body.{object}

So I am making request to twitch to get some streamer data using npm response.

var express = require('express');
var router = express.Router();
var request = require('request');

/* GET users listing. */
router.get('/streams/:user', function(req, res, next) {

    request('https://api.twitch.tv/kraken/streams/' + req.params.user, function ( error, response, body) {
        if (!error && response.statusCode == 200)
        {
            res.send(body);
        } 
        else 
        {
            res.send(404);
        }
    });
});

module.exports = router;

When I do res.send(body) it gives me back my json object printed to screen nicely.

{"_links":{"self":"https://api.twitch.tv/kraken/streams/allencoded","channel":"https://api.twitch.tv/kraken/channels/allencoded"},"stream":null}

So I want to not get all that back but instead just get the self url. I then thought I would do something like:

res.send(body._links.self)

That returned nothing but a blank screen.

How do print out just the self url?

like image 908
allencoded Avatar asked Mar 29 '15 19:03

allencoded


2 Answers

This question is little old, yet, the following also seems more helpful. In request, you can pass json: true and request library returns you the json object.

replace following line,

request('https://api.twitch.tv/kraken/streams/' + req.params.user, function ( error, response, body) {

with the one below

request({'url':`https://api.twitch.tv/kraken/streams/${req.params.user}`, 'json': true }, function ( error, response, body) {
like image 183
mdsadiq Avatar answered Oct 26 '22 09:10

mdsadiq


body is a string. You have to parse it as JSON first:

res.json(JSON.parse(body)._links.self);
like image 28
mscdex Avatar answered Oct 26 '22 08:10

mscdex