【问题标题】:Passing response from API as response from my node server throws将来自 API 的响应作为来自我的节点服务器的响应传递抛出
【发布时间】:2019-07-25 03:27:39
【问题描述】:

在某些情况下,当在我的节点/express 服务器上命中特定路由时,我想向 API 发出请求并将该响应直接返回给客户端。我关注了这个堆栈溢出帖子:Send response from server side axios request to React/Redux app

创建这个:

router.use('/', async (req, res) => {
  const apiUrl = `https://assets.scratch.mit.edu${req.url}`;
  console.log(apiUrl);
  const scratchResponse = await axios.get(apiUrl);
  try {
    res.send(scratchResponse);
    console.log('worked!', apiUrl);
  } catch (error) {
    console.log('error in assets get request', apiUrl, error);
    res.sendStatus(500);
  }
});

这适用于某些请求,但会因错误而中断其他请求:

TypeError: Converting circular structure to JSON

根据此堆栈溢出帖子的建议:JSON.stringify, avoid TypeError: Converting circular structure to JSON

我已尝试通过添加此导入来使用 npm flatted 库:

const { stringify } = require('flatted/cjs');

在我回复之前进行字符串化:

res.send(stringify(scratchResponse));

但似乎正在删除一些对客户端至关重要的信息(客户端中断并说它缺少属性)。

是否可以直接发送我从 API 收到的响应?

【问题讨论】:

标签: node.js express axios


【解决方案1】:

嗯,最简单的方法可能是将响应传递给客户端:

  router.get('/', (req, res) => {
    axios({
      method: 'get',
      url: apiUrl,
      responseType: 'stream'
    })
      .then(function(response) {
        response.data.pipe(res)
    });
  });

如果第三方的格式存在问题,您仍然不走运,但这至少会使您的服务器端处理成为问题,并且性能应该会更好一些因为您只是将响应向下传递而不是在服务器上获取完整响应,因此将其序列化为 JSON 只是为了将其重新发送到响应流。

【讨论】:

  • responseType: 'stream' 是我们所缺少的,谢谢!
  • 仅供参考:使用管道发送流响应时,前端不提供像“content-disposition”这样的响应标头。寻找解决方案 RN。
猜你喜欢
  • 2011-01-26
  • 2023-04-11
  • 1970-01-01
  • 1970-01-01
  • 2016-01-17
  • 2020-03-24
  • 1970-01-01
  • 1970-01-01
  • 2021-12-15
相关资源
最近更新 更多