node.js - 如何通过 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
}
如何创建客户端从该对象发送的相同表单数据?
解决方案
如果我理解正确,您希望在客户端向您的微服务发送请求并且服务器收到该请求后将此文件对象发送到特定的 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模块。
推荐阅读
- javascript - 固定/粘性位置对象的颜色变化
- javascript - 使用 jquery sum 字段输入值
- javascript - 如何在 nativescript 中显示/隐藏元素?
- excel - 找到更新表的用户表单存储行信息
- kubernetes - 当我们扩展 kubernetes 部署并更改其中一个 pod 或容器配置时会发生什么?
- python - 使用python检查文本文件的每一行中的内容(初学者)
- python - Django 1.11 - 我如何确保 TruncYear 产生祖鲁时间
- javascript - 如何用 php scritp 填充 html 表单,得到数组?
- angularjs - 从其他指令调用指令
- ionic3 - 如何从 http 请求中读取和重新注入响应数据