后端的 axios psot 请求获取图像"/>
如何通过向 node.js 后端的 axios psot 请求获取图像
在这篇文章的帮助下,我正在尝试使用 axios 将图像从反应前端发送到 node.js 后端: images-to-node-js-with-axios 我设法从前端到后端获取它,但是当我控制台记录 req.files 和 req.body 时,它是未定义的或空的。而且我不知道如何解决它。谁能帮帮我?
这里是 app.js 反应前端的代码:
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);
});
当我只记录请求时,我得到对 axios 的响应正在向后端发送一些东西,当我在浏览器中查看网络和 sonsole 时,我得到以下信息:
提前感谢您的帮助!!
回答如下:更多推荐
如何通过向 node.js 后端的 axios psot 请求获取图像
发布评论