Node.js 节点-调用ExpressJS路由,并需要对其中的API执行GET请求

Node.js 节点-调用ExpressJS路由,并需要对其中的API执行GET请求,node.js,express,request,node-https,Node.js,Express,Request,Node Https,我正在为一个项目制作一个加密货币仪表板,我对Node和Express完全陌生。这就是我目前拥有的 app.get('/search', function(req,res){ res.writeHead(200, {'Content-Type': 'text/html'}); res.write(req.url); data = [] var options = { "method": "GET", "hostname": "rest

我正在为一个项目制作一个加密货币仪表板,我对Node和Express完全陌生。这就是我目前拥有的

app.get('/search', function(req,res){
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(req.url);
    data = []
    var options = {
        "method": "GET",
        "hostname": "rest.coinapi.io",
        "path": "/v1/assets",
        "headers": {'X-CoinAPI-Key': 'MY_API_KEY_HERE'}
    };

    const request = https.request(options, (data, response) => {    
        response.on('data', d => {
            data.push(d);
        })
    });
    console.log(data);
    request.end();
    res.end();
})
我的想法是在我的前端,我有一个按钮,点击后,将向CoinAPI发出请求,获取所有报告的资产和当前值。我不太确定应该如何将响应数据作为响应发送回我的前端。因此,我试图从
https.request
行返回的JSON中提取响应数据。我有一个数据数组
data=[]
,您可以在我的代码顶部看到

我最初将我的请求设置为:

const request = https.request(options, response => { 
但是当我试图将
d
推到
数据上时,我记录了控制台日志,数据数组是空的。这是有道理的,
数据
数组超出了请求函数的范围,因此数据不会得到更新。但是当我试图将
数据
传递到函数中时,我出错了


基本上,我希望在向CoinAPI发出请求后能够将JSON数据发送回我的前端。如果我在我的
https.request
回调中执行
process.stdout.write(d)
,我确实看到coinapi数据返回。我只是不知道如何把它发送到前端,作为我回应的一部分

要将JSON数据作为响应发送回客户端,只需执行以下操作:

return res.json(data);

就这么简单。:)

问题:

app.get('/search', function(req,res){
  let str = '';
  const options = {
    "method": "GET",
    "hostname": "rest.coinapi.io",
    "path": "/v1/assets",
    "headers": {'X-CoinAPI-Key': 'MY_API_KEY_HERE'}
  };

  const request = https.request(options, (response) => {
      response.on('data', d => {
        str += d;
      });
      response.on('end', () => {
        try {
          let obj = JSON.parse(str);
          // do any manipulation here
          res.json(obj);
        } catch(e){
          console.log(e);
          res.status(500).json({ message: 'Something went wrong - parse error' });
        }
      });
  });
  request.end();

  request.on('error', (e) => {
    console.log(e);
    res.status(500).json({ message: 'Something went wrong - req error' });
  });
});
  • (数据、响应)
    的使用不正确。第一个也是唯一一个参数是
    response
    ,因此它应该是
    (response)

  • on('data')
    事件接收缓冲数据。将其连接到最终字符串是标准用法,而不是附加数组

  • 您在('end')
上缺少一个
,您应该使用它来输出最终数据或进行任何处理

  • 使用
    res.write
    可以发送
    text/html
    内容类型和一些您不想要的内容,如果目标是输出前端可以解析和使用的JSON

  • 缺少API调用的错误处理程序

  • 完成更新代码:

    app.get('/search', function(req,res){
      let str = '';
      const options = {
        "method": "GET",
        "hostname": "rest.coinapi.io",
        "path": "/v1/assets",
        "headers": {'X-CoinAPI-Key': 'MY_API_KEY_HERE'}
      };
    
      const request = https.request(options, (response) => {
          response.on('data', d => {
            str += d;
          });
          response.on('end', () => {
            try {
              let obj = JSON.parse(str);
              // do any manipulation here
              res.json(obj);
            } catch(e){
              console.log(e);
              res.status(500).json({ message: 'Something went wrong - parse error' });
            }
          });
      });
      request.end();
    
      request.on('error', (e) => {
        console.log(e);
        res.status(500).json({ message: 'Something went wrong - req error' });
      });
    });
    
    我添加了一个
    JSON.parse()
    ,以显示如果您想在将数据发送到前端之前对其进行一些操作,您将如何处理它。如果只想返回coin API的准确响应,请使用
    end
    事件,如:

    response.on('end', () => {
      res.json(str);
    });