传递来自 API 的响应作为来自我的节点服务器的响应抛出 [英] Passing response from API as response from my node server throws

查看:24
本文介绍了传递来自 API 的响应作为来自我的节点服务器的响应抛出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在某些情况下,当我的节点/快递服务器上遇到特定路由时,我想向 API 发出请求并将该响应直接返回给客户端.我关注了这个堆栈溢出帖子:Send response from服务器端 axios 请求 React/Redux 应用

In certain cases, when a specific route is hit on my node/express server, I would like to make a request to an API and return that response directly to the client. I followed this stack overflow post: 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);
  }
});

这对某些请求有效,但对于其他请求会因错误而中断:

This is working for some of the requests, but breaks for others with the error:

TypeError: Converting circular structure to JSON

根据此堆栈溢出帖子的建议:JSON.stringify,避免 TypeError:将循环结构转换为 JSON

Per the suggestions from this stack overflow post: JSON.stringify, avoid TypeError: Converting circular structure to JSON

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

I have tried using the npm flatted library by adding this import:

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

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

and stringifying before my response:

res.send(stringify(scratchResponse));

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

But it seems like some information is being removed that is critical to the client (client breaks and says it is missing properties).

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

Is it possible to directly send the response I'm receiving from the API?

推荐答案

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

Well, the easiest way would probably be to pipe the response down to the client:

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

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

If there's an issue with the format from the third party, you're still out of luck, but this will at least take your server-side processing out of the mix as the problem, and also performance should be a little better since you're just piping the response down rather than getting the full response on the server, serializing it to JSON only to re-send it to the response stream.

这篇关于传递来自 API 的响应作为来自我的节点服务器的响应抛出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆