从NodeJS / Express发送JSON响应

对于这个问题我很抱歉,所以我希望你们能把我放在正确的方向。

我正在制作一个应用程序,通过NODEJS从REST API检索数据。 (这是一个成功的作品)。

然后,我有一个监听URL(我自己的API),通过转到浏览器http:// localhost / api或使用POSTMAN来调用。 到目前为止,我看到在控制台(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; 

非常感激!

要从快递服务器发送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 }); 

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

 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', 'User-Agent': 'my-reddit-client' } }; app.get("/api", function(req, res) { request(options, function(err, output, body) { var json = JSON.parse(body); console.log(json); // Logging the output within the request function res.json(json) //then returning the response.. The request.json is empty over here }); //closing the request function }); app.listen(3000, function() { console.log("My API is running..."); }); module.exports = app;