【问题标题】:Parse response body from request and return back to client从请求中解析响应正文并返回给客户端
【发布时间】:2020-05-09 18:17:02
【问题描述】:

一般来说,我是 node.js 和 JavaScript 的新手,但我正在尝试将 node.js 用作简单的 REST API。客户端请求到达 node.js,然后 node.js 到达数据库以执行 crud 操作并返回响应。但是,我希望能够解析此响应并在发送回客户端之前将其格式化为我自己的 JSON。现在我使用请求库和.pipe() 发回。我可以将.pipe() 转换成一个我可以解析的变量,还是我需要完全改变我的方法?

这是我的代码目前的样子:

const request = require('request');

var username = "admin";
var password = "admin";
var auth = "Basic " + new Buffer(username + ":" + password).toString("base64");

exports.getPosts = (req, res, next) => {
    request({
        uri: 'http://localhost:8000/LATEST/search?q=caesar',
        headers: {"Accept": "application/json",
                "Authorization": auth
        }   
    }).pipe(res);

};

我知道request 已被弃用,因此目前可能有更好的方法来执行此操作。感谢任何帮助和反馈,因为我是新手。

【问题讨论】:

    标签: javascript node.js request pipe


    【解决方案1】:

    您可以使用request 模块或axios 或任何东西。您可以保存 JSON 正文并对其进行处理并将其发送给客户端。下面是如何做到这一点。

    const request = require('request');
    
    var username = "admin";
    var password = "admin";
    var auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
    
    exports.getPosts = (req, res, next) => {
      request({
        uri: 'http://localhost:8000/LATEST/search?q=caesar',
        headers: {
          "Accept": "application/json",
          "Authorization": auth
        }
       // You can set json:true here so that you don't have to do JSON.parse below.
      }, (err, response, body)=>{
        //body is the json body
        const jsonBody = JSON.parse(body);
        //do something with json request
        res.json(jsonBody);
      })
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-09
      • 1970-01-01
      • 2018-10-09
      • 1970-01-01
      • 2013-08-07
      • 2020-08-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多