后端获取图片?"/>
如何通过Axios POST请求到node.js后端获取图片?
在这篇文章的帮助下,我正在尝试使用 axios 将图像从反应前端发送到 node.js 后端:How do you send images to node js with Axios? I managed to get it from the frontend到后端,但是当我
console.log
req.files
和 req.body
它是 undefined
或空的。我不知道如何解决它。谁能帮帮我?
这是
app.js
React 前端的代码:
import "./App.css";
import React, { useState } from "react";
import axios from "axios";
function App() {
const [image, setImage] = useState("");
function handleImage(e) {
console.log(e.target.files);
setImage(e.target.files[0]);
}
function handleApi() {
const formData = new FormData();
formData.append("image", image);
console.log(formData)
axios
.post("http://localhost:3001/users/editprofile/1", formData, {
headers: {
"Content-Type": "multipart/form-data",
},
})
.then((res) => {
console.log(res);
});
}
return (
<div>
<input type="file" name="file" onChange={handleImage} />
<button onClick={handleApi}>submit</button>
</div>
);
}
export default App;
这是 node.js 后端:
router.post("/editprofile/:id", async (req, res) => {
const id = req.params.id;
console.log(req.files)
console.log(req.body)
//console.log(req)
//const { pfp } = req.files;
// if (pfp) {
// await pfp.mv(`${__dirname}/images/profile_pictures/pfp_${id}}`);
// }
//Would make the code "save" by not allowing any uploads at allz`
//if (/^image/.test(image.mimetype)){
// console.log("not an image");
// return res.sendStatus(400);
//}
res.sendStatus(200);
});
当我只记录
req
时,我收到 Axios 正在向后端发送内容的响应,当我在浏览器中查看网络和控制台时,我得到以下内容:
浏览器中的网络选项卡:
浏览器中的控制台:
提前感谢您的帮助!!
回答如下:问题出在服务器端,您缺少表单/多部分请求处理中间件。
常用的工具是multer
因此,在您的路线上,您需要添加上传中间件,然后您可以通过
req.file
(或req.files
,如果有多个文件,请查看文档)访问文件。
在此之前,您需要在设置位置(目标)、文件名和 mimetype 检查器的位置设置上传中间件。
此外,您可以在那里阅读
req.params.id
并将其用作文件名,还可以添加图像过滤器,而不是在路径中。
试试这个:
路由器:
const myUploadMiddleware = require('./upload');
router.post("/editprofile/:id", myUploadMiddleware, async (req, res) => {
console.log('editprofile', req.body, req.file);
res.sendStatus(200);
});
上传中间件:
const multer = require('multer');
const storage = multer.diskStorage({
// my destination here
destination: function(req, file, cb) {
cb(null, `${__dirname}/images/profile_pictures/`)
},
// my custom filename here
filename: function(req, file, cb) {
//const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
//cb(null, file.fieldname + '-' + uniqueSuffix)
const id = req.params.id;
cb(null, `pfp_${id}`);
}
});
// my mimetype check here
const fileFilter = (req, file, cb) => {
if (!file.mimetype.includes('image')) {
return cb(new Error('not an image'));
}
cb(null, true);
};
// also field name here image has to correspond to image on the frontend
// formData.append("image", image);
const upload = multer({
storage: storage,
fileFilter
}).single('image');
module.exports = upload;
更多推荐
如何通过Axios POST请求到node.js后端获取图片?
发布评论