从NodeJS / Express

时间:2017-07-16 13:08:31

标签: javascript json node.js express

对不起n00b问题,我有点被困,所以我希望你们能让我朝着正确的方向前进。

我正在创建一个由NODEJS从REST API检索数据的应用程序。 (这是成功的并且有效。)

然后,我通过转到浏览器http://localhost/api或使用POSTMAN调用express中的listen URL(我自己的API)。到目前为止一切顺利,我在控制台(NODE控制台)中看到我的请求得到了完美的处理,因为我看到了JSON响应,但是,我还希望在浏览器或POSTMAN中看到JSON响应作为JSON响应,而不仅仅是控制台我知道我在我的(简单)代码中遗漏了一些东西,但我刚开始....请帮助我这里是我的代码。

var express = require("express"); 
var app = express();
const request = require('request');

const options = {  
    url: 'https://jsonplaceholder.typicode.com/posts',
    method: 'GET',
    headers: {
        'Accept': 'application/json',
        'Accept-Charset': 'utf-8',
    }
};

app.get("/api", function(req, res)  { 
    request(options, function(err, res, body) {  
    var json = JSON.parse(body);
    console.log(json);
    });
    res.send(request.json)
    });

app.listen(3000, function() {  
    console.log("My API is running...");
});

module.exports = app;

非常感谢!

2 个答案:

答案 0 :(得分:4)

要将快速服务器的json响应发送到使用res.json(request.json)而不是res.send(request.json)的前端。

app.get("/api", function(req, res)  { 
  request(options, function(err, res, body) {  
    var json = JSON.parse(body);
    console.log(json); // Logging the output within the request function
  }); //closing the request function
  res.send(request.json) //then returning the response.. The request.json is empty over here
});

尝试这样做

app.get("/api", function(req, res)  { 
  request(options, function(err, response, body) {  
    var json = JSON.parse(body);
    console.log(json); // Logging the output within the request function
    res.json(request.json) //then returning the response.. The request.json is empty over here
  }); //closing the request function      
});

答案 1 :(得分:3)

非常感谢ProgXx,结果我使用了相同的res和响应名称。这是最终的代码。非常感谢ProgXx

[:alnum:]
相关问题