【问题标题】:react axios send headers do api反应 axios 发送标头做 api
【发布时间】:2020-04-14 20:58:39
【问题描述】:

如何发送 api 请求、发送文件和文本以一种形式。

我用

"Content-Type": "multipart/form-data",

但是,我得到了返回 PHP

<b>Warning</b>:  Missing boundary in multipart/form-data POST data in <b>Unknown</b> on line <b>0</b><br />
{"errors":{"userName":["The user name field is required."],"userEmail":["The user email field is required."],"userAbout":["The user about field is required."],"userPhone":["The user phone field is required."]}}

我填写了所有的表单输入 我只使用一个 FORM 发送图像和文本的问题

我的反应函数

onCreate = (event) => {
        event.preventDefault();

        const { avatar, userName, userEmail, userPhone, userAbout } = this.state;

        axios
            .post(
                api + "api/profile",
                {
                    avatar,
                    userName,
                    userEmail,
                    userAbout,
                    userPhone,
                },

                {
                    headers: {
                        "Content-Type": "multipart/form-data",
                        Authorization: reqtoken,
                    },
                }
            )

            .then(
                (response) => {

                    if (response.status == 201) {
                        alert("We will be in touch soon");

                    }
                    if (response.status != 201) {
                        alert("Something wrong");
                    }
                },
                (error) => {
                    console.log(error);
                    alert("Connection Failure");
                }
            );
        this.resetForm();
    };

【问题讨论】:

  • 请分享您请求的 curl 等效项

标签: php reactjs axios


【解决方案1】:

在你的情况下,你可以像这样使用 axios

import axios from 'axios';

const handleFileUpload = (file) => {
    const formData = new FormData();
    const apiUrl = YOUR_API_URL
    formData.append('file', file)
    const config = {
        headers: {
            'content-type': 'multipart/form-data'
        }
    }
    return axios.post(apiUrl, formData, config)
}

【讨论】:

  • 我在 php 上获取文件但 $request->file 返回 null 我使用标题:{ "Content-Type": "multipart/form-data",
  • 你用过formdata吗
  • 是的,如果我使用 dd($request->all()); 可以看到数据;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-01-05
  • 2020-02-13
  • 2018-12-28
  • 2019-05-12
  • 2017-10-29
  • 1970-01-01
  • 2021-08-18
相关资源
最近更新 更多