[英]Getting req.body and req.file as empty when uploading file with axios
这是前端:
let file = this.$refs.file.files[0] //"this" refers to vue
let data = new FormData();
data.append("image", file, file.fileName);
data.append("content", this.content);
data.append("title", this.title);
data.append("action_type", "add_article");
axios
.post("http://localhost:3000/api", data, {
headers: {
// "accept": "application/json",
// "Accept-Language": "en-US,en;q=0.8",
// "Content-Type": `multipart/form-data; boundary=${data._boundary}`,
// "auth": util.getCheckedToken(),
'content-type': 'multipart/form-data'
}
})
.then(response => {
alert("success!", response);
})
.catch(error => {
alert("fail!", error);
});
后端的某些部分:
app.use(multer({
storage: multer.diskStorage({
destination: (req, file, cb) => { cb(null, '../static/images'); },
filename: (req, file, cb) => { cb(null, my_random.fileName(file.originalname)); }
}),
fileFilter: (req, file, cb) => { cb(null, "image/png image/jpg image/jpeg".split(' ').includes(file.mimetype)); }
}).single('image'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
查看我正在使用的工具的标签。 我没有收到任何错误消息,并且 req.file 和 req.body 为空。 问题的原因可能是什么?
尝试发送文本/csv 文件时遇到类似问题,通过在路由之前解析内容类型来解决。 像这样:
app.use(bodyParser.raw({type: multipart/form-data}));
前
app.use(multer({}))
bodyParser.raw([options]) 返回将所有主体解析为 Buffer 的中间件,并且仅查看 Content-Type header 与类型选项匹配的请求
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.