从 node.js 中的 stackoverflow api 获取垃圾 JSON

getting garbage JSON from stack-overlfow api in node.js

我正在使用 Whosebug API 搜索问题。 这是我的代码:

app.get('/sof',function(req,res){
  var ark;
  request("https://api.stackexchange.com/2.2/search/advanced?order=desc&sort=relevance&q=python%20best%20practices&site=Whosebug", function(error, response, body) {
    ark = body;
    console.log(body);
  res.send(ark);
  });
});

但是,我在浏览器和日志中收到垃圾值机器人。

我怎样才能解决这个问题?其他一切都 运行 没问题。

我也在使用 body-Parser:

var bodyParser = require('body-parser');
app.use(bodyParser.json());

编辑: 这是@Wainage 在评论中解释的代码。

app.get('/sof', function(req, res){
    request.get({ url: "https://api.stackexchange.com/2.2/search/advanced?order=desc&sort=relevance&q=python%20best%20practices&site=Whosebug",
                  gzip: true },
        function(error, response, body) {
        console.log(body);       // I'm still a string
        body = JSON.parse(body); // Now I'm a JSON object

        res.json(body); // converts and sends JSON
    });
});

你被回调给绊倒了。 res.send 将在结果输入之前触发。

app.get('/sof',function(req,res){
  var ark;
  request("https://api.stackexchange.com/2.2/search/advanced?order=desc&sort=relevance&q=python%20best%20practices&site=Whosebug", function(error, response, body) {
    ark = body;
    console.log(body);
    // res only when you get results

    //res.send(ark);
    res.json(body); // converts and sends JSON
  });
});

应该可以。

编辑:(包括这个特定问题的 gzip 压缩)

根据 StackExchange docs 他们的结果返回 gzip'd(有意义)。你需要告诉请求是这样的。

app.get('/sof', function(req, res){
    request.get({ url: "https://api.stackexchange.com/2.2/search/advanced?order=desc&sort=relevance&q=python%20best%20practices&site=Whosebug",
                  gzip: true },
        function(error, response, body) {
        console.log(body);       // I'm still a string
        body = JSON.parse(body); // Now I'm a JSON object

        res.json(body); // converts and sends JSON
    });
}