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

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

问题描述

在某些情况下,当在我的节点/表达服务器上命中特定路由时,我想向API发出请求,并将该响应直接返回给客户端.我遵循了这个堆栈溢出的帖子:发送来自服务器端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.字符串化,避免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天全站免登陆