首页 > 解决方案 > 如何通过 Node.js 将表单数据从客户端重新路由到某个微服务?

问题描述

我在 Node.js 上创建了一个中间后端来与我的应用程序所依赖的多个微服务通信。到目前为止一切都很好。我无法解决的问题是文件处理。我的客户端正在以 Formdata 的形式将文件发送到 Node 层,我想将相同的表单数据重新路由到某个特定的微服务,该微服务也需要表单数据形式的文件。我正在使用express-fileupload中间件从req对象中提取文件,但它为我提供了具有以下属性的文件数据:

req.files.file = {
  data:Buffer(47643) [37, 80, 68, …]
  encoding:"7bit"
  md5:() => …
  mimetype: "application/pdf"
  mv: function (filePath, callback) { … }
  name:"somefile.pdf"
  truncated:false
}

如何创建客户端从该对象发送的相同表单数据?

标签: node.jsfileexpressmultipartform-data

解决方案


如果我理解正确,您希望在客户端向您的微服务发送请求并且服务器收到该请求后将此文件对象发送到特定的 api。您的文件数据可通过req所有快速中间件中的对象访问。

next借助express 方法,您可以轻松地在中间件或下一个路由之间进行路由。

app.post('/upload', function(req, res, next) {
  console.log(req.files.foo); // the uploaded file object
  if (/*go to next middleware*/)
     next();
  else if (/*go to next route*/)
     next('route');
}, function (req, res) {
  // [next middleware]
  // req.files.foo is accessible
});

// specific api should stand exactly after receiver api
app.post('/anyRoute', function(req, res) {
  // [next route]
  console.log(req.files.foo); // object file is already accessible
});

如果你想从服务器发出请求,你可以使用axios模块。


推荐阅读