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

15,101

Solution 1

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

res.json(JSON.parse(body)._links.self);

Solution 2

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) {
Share:
15,101
allencoded
Author by

allencoded

Updated on June 08, 2022

Comments

  • allencoded
    allencoded almost 2 years

    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?

  • allencoded
    allencoded about 9 years
    I literall just figured this out by doing var obj = JSON.parse(body); res.send(obj._links);
  • Mohammad Kermani
    Mohammad Kermani almost 6 years
    Works as expected. Thanks
  • Mohammad Kermani
    Mohammad Kermani almost 6 years
    is not possible to request for JSON instead of converting? Lie the answer below which I guess it should work with the better performance