【问题标题】:Forward multipartform request from one GraphQL API to other GraphQL API将多部分请求从一个 GraphQL API 转发到另一个 GraphQL API
【发布时间】:2021-06-16 05:36:10
【问题描述】:

我正在通过多部分请求将文件从浏览器上传到由 express 提供支持的 graphql-yoga 支持的 GraphQL-API。 现在我想将这个完全相同的请求正文转发到另一个 GraphQL-API。

const fetch = require('node-fetch');

async passThrough(args, opts) {
  const { body, getRawBody, headers, method } = opts.request;
  var rawBody;
  if (body.files && body.files.length) {
    rawBody = await getRawBody;
  } else {
    rawBody = typeof body == 'string' ? body : JSON.stringify(body)
  }
  let options = {
    body: rawBody,
    method, headers
  };
  var res = await fetch(otherApiUrl, options).then((res) => {
    return res.json();
  });
  return res;
}

在这个函数中,我将身体作为一个对象。但它包括“文件”作为我不能简单转发的承诺(找不到任何事情要做)。所以我尝试通过快速中间件获取原始正文,并像上面一样使用 await getRawBody 访问它。

function getRawBody(req, res, next) {
  req.getRawBody = new Promise(resolve => {
    var buf = '';
    req.on('data', x => buf += x);
    req.on('end', () => {
      resolve(buf);
    });
  });
  next();
}

server.express.use(getRawBody);

它将请求传递给其他 API,但文件不再是有效的 jpeg。我发现,上传的文件从原始文件中移动了一些位。我可能做错了什么?

【问题讨论】:

    标签: javascript express file-upload graphql multipartform-data


    【解决方案1】:

    我找到了解决方案here 并调整了函数以获取原始主体。现在文件内容不再在目标主机上移动。

    const concatStream = require('concat-stream');
    function getRawBody(req, res, next) {
      req.getRawBody = new Promise(resolve => {
        req.pipe(concatStream(function (data) {
          resolve(data);
        }));
      });
      next();
    }
    

    【讨论】:

      猜你喜欢
      • 2018-02-08
      • 2016-12-14
      • 2021-04-08
      • 2017-05-07
      • 2019-11-13
      • 2017-02-04
      • 2019-08-30
      • 2014-06-07
      • 1970-01-01
      相关资源
      最近更新 更多