如何通过向 node.js 后端的 axios psot 请求获取图像

编程入门 行业动态 更新时间:2024-10-06 09:22:29

如何通过向 node.js <a href=https://www.elefans.com/category/jswz/34/1771414.html style=后端的 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 请求获取图像

本文发布于:2024-05-30 16:09:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1770678.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:后端   图像   js   node   axios

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!