问题描述
所以在第一台服务器上我有这样的路由:
So on first server I have route like this:
const express = require('express');
const router = express.Router();
const FormData = require('form-data');
const fetch = require('node-fetch');
const multer = require('multer');
const storage = multer.memoryStorage();
const upload = multer({ storage });
router.post('/', upload.single('file'), async (req, res) => {
const form = new FormData();
form.append('folderId', req.body.folderId);
form.append('file', req.file.buffer, req.file.filename);
const result = await fetch('http://localhost:3003/users', { method: 'POST', body: form }).then(res => res.json());
res.json(result);
})
在这台服务器上,它工作正常,我可以看到 req.file 和它的缓冲区.所以我想把这个文件(不把它存储在第一台服务器上,它只存在于内存和缓冲区中)到另一个.
On this server, it works fine, I can see req.file and it's buffer. So I wanna send this file (without storing it on first server, it exists only in memory and as buffer) to another.
其他服务器路由是这样的:
Other server route is like this:
const express = require('express');
const router = express.Router();
const multer = require('multer');
const path = require('path');
const putanja = path.join(__dirname, '../uploads/users');
const storage = multer.diskStorage({
destination: (req, file, cb) => {
console.log('entered here?')
if (!req.body.folderId) return cb({ message: 'no folderId' });
if (!fs.existsSync(putanja + '/' + folderId)) fs.mkdirSync(putanja + '/' + folderId);
cb(null, putanja + '/' + folderId);
},
filename: (req, file, cb) => cb(null, file.originalname)
});
const upload = multer({ storage });
const fs = require('fs');
router.post('/', upload.single('file'), async (req, res) => {
console.log(req.body)
console.log(req.file)
res.json({ status: 'ok' })
})
所以在第二台服务器上,它甚至没有进入multer中间件,req.file总是被定义,而console.log('entered here?')从来没有被看到过.看起来我没有以多部分形式传递数据?
So on second server, it doesn't even enter the multer middleware, req.file is always defined, and that console.log('entered here?') is never seen. Looks like I'm not passing data as multipart-form?
另外,当第二个服务器通过邮递员直接向它发送文件时,它可以工作.
Also, second server, when sending file directly to it via postman, works.
所以我的问题是,我如何发送该文件?作为缓冲?溪流?Base64?我想我尝试了一切,甚至将 node-fetch 更改为 request,但仍然没有运气.
So my question, how do I send that file? As a buffer? Stream? Base64? I think I tried everything, even changed node-fetch to request, but still no luck.
推荐答案
所以在第二台服务器上,它甚至没有进入multer中间件,req.file总是定义的,并且console.log('entered在这里?')从未见过.看起来我没有以多部分形式传递数据?
所以这意味着你的第二个服务器不理解请求的 Content-Type.
So this mean your second server doesn't understand the Content-Type of request.
因此,当您向第二台服务器发送请求时,请在标头中添加 Content-Type 参数
So do one thing add Content-Type parameter in header when you are sending request to second server
将 Content-Type 添加到 multipart/form-data或者如果您不知道传递标题:{内容类型":未定义} http 会为你设置header
Add Content-Type to multipart/form-dataor if you don't know pass headers : { 'Content-Type' : undefined } http will set header for you
这篇关于将文件从一个节点 js 服务器发送到另一个节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!