微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 从NodeJS / Express发送JSON响应

对不起n00b问题我有点卡住所以我希望你们能让我朝着正确的方向前进.

我正在制作一个由NODEJS从REST API检索数据的应用程序. (这是成功和有效的).

然后,我通过转到浏览器http://localhost/api或使用POSTMAN调用一个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;

非常感激!

解决方法:

要从快速服务器向前端发送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      
});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐