【问题标题】:How to post/send an image to an API using Axios?如何使用 Axios 将图像发布/发送到 API?
【发布时间】:2022-01-25 08:28:26
【问题描述】:

我正在尝试通过 axios 将图像发布/发送到 API。

这是我的前端代码(ReactJS):

const handleImage = (e) => {
    const myImg = e.target.files[0];

    const config = {
        headers: {
            "Content-Type": "multipart/form-data"
        }
    };

    if (myImg !== undefined) {
        let form = new FormData();

        form.append("file", myImg);

        axios.post("/upload", form, config)
            .then(res => console.log(res))
            .catch(err => console.log(err));
    }
}

这是我的后端代码(NodeJS & ExpressJS):

app.post("/upload", (req, res) => {
    console.log(req.body);
    res.send(req.body);
});

console.log(req.body) 在控制台窗口上打印一个空对象,即{}

所以,简而言之,我的疑问是为什么它打印一个空对象?我的代码中是否缺少某些内容?

【问题讨论】:

    标签: image axios


    【解决方案1】:

    这可能是因为您的后端尚未准备好接收上传的文件。

    您可以使用名为 Multer 的库,这将使您更轻松地设置后端以支持文件上传。

    有很多内容解释了如何使用 Multer。您可以查看this one out

    【讨论】:

      猜你喜欢
      • 2017-02-01
      • 1970-01-01
      • 2020-09-03
      • 1970-01-01
      • 1970-01-01
      • 2021-11-26
      • 2020-10-28
      • 2021-08-29
      • 2021-03-24
      相关资源
      最近更新 更多