0

I'm trying to request the json file from stackexchange api and when the server loads save it on the client side so I can manipulate/change it locally.

I tried using this code but page just keep loading and nothing happens.

const express = require('express');
const bodyParser = require('body-parser');
const request = require('request');

const app = express();

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json)

const surl = 'https://api.stackexchange.com/2.2/users/11097431?order=desc&sort=reputation&site=stackoverflow';

app.use('/', (req, res, next) => {
    request(surl, (error, response, body) => {
        // res.setHeader("Content-Type", "application/json; charset=utf-8");
        res.json(body)
        console.log('body:', body);
        console.log('body:', req.body);
    });
});

app.listen(3000, () => { console.log('On port 3000...') });

And if I comment out these two lines in my code below

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json)

It gives this kind of output.

"\u001f�\b��\u0000��8z00\u0000^{4���=�c��\u0000��#c�\u0002\u0000\u0000"

If anyone could give me a start that would be great! Thanks.

fuzious
  • 400
  • 5
  • 19
Aman Raj
  • 239
  • 3
  • 15

1 Answers1

2

The output is gibberish because body is gzip compressed. It's not JSON, not even text:

enter image description here

To return it to browser, the easiest way is using pipe:

const request = require('request');
const surl = 'https://api.stackexchange.com/2.2/users/11097431?order=desc&sort=reputation&site=stackoverflow';

app.use('/', (req, res) => {
  request(surl).pipe(res);
});

Or, if you want to manipulate/change the body, gzip: true option can be used:

const request = require('request');
const surl = 'https://api.stackexchange.com/2.2/users/11097431?order=desc&sort=reputation&site=stackoverflow';

app.use('/', (req, res) => {
  request({
    url: surl,
    gzip: true
  }, function(error, response, body) {
    let bodyObj = JSON.parse(body);
    // change bodyObj...
    res.json(bodyObj);
  });
});
shaochuancs
  • 15,342
  • 3
  • 54
  • 62