首页 文章

从NodeJS / Express发送JSON响应

提问于
浏览
4

对不起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 回答

  • 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      
    });
    
  • 2

    非常感谢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;
    

相关问题