无法使用前端 react/axios 将带有 encType="multipart/formdata" 的 formdata 发送到后端节点/multer

时间:2021-06-25 18:01:07

标签: reactjs axios

我正在使用 FormData 使用 axios 将信息从表单发送到我的后端,但是当我打印数据时,它返回内容类型:“application/json”,这使我无法发送文件以在 multer 上处理.

我尝试包含配置类型并将其包含在表单中,但没有任何效果...当我尝试在节点上打印它时,我也得到了 undefienid 作为答案。

表格:

<form
                                className="formularioContato"
                                encType="multipart/form-data"
                                onSubmit={handleSand}
                            >
                                <input
                                    type="text"
                                    placeholder="Nome completo"
                                    onChange={(e) => setName(e.target.value)}
                                    required
                                />
                                <input
                                    type="text"
                                    placeholder="Celular"
                                    onChange={(e) => setTelephone(e.target.value)}
                                    required
                                />
                                <input
                                    type="email"
                                    placeholder="E-mail"
                                    onChange={(e) => setEmail(e.target.value)}
                                    required
                                />
                                <label htmlFor="arquivo" className="arquivo">
                                    <span>Selecionar arquivo</span>Anexe seu currículo
                                </label>
                                <input
                                    type="file"
                                    id="arquivo"
                                    name="cv"
                                    placeholder="Currículo (Anexar documento)"
                                    onChange={(e) => setFile(e.target.files[0])}
                                    required
                                />
                                <textarea
                                    placeholder="Mensagem"
                                    onChange={(e) => setMessage(e.target.value)}
                                ></textarea>
                                <button type="submit" className="button--azul">
                                    Enviar
                                </button>

                                <label>
                                    <input type="checkbox" required />
                                    Eu li, estou ciente das condições de tratamento dos meus dados
                                    pessoais e dou meu consentimento, quando aplicável, conforme
                                    descrito nesta{' '}
                                    <Link to="/cookies">política de privacidade</Link>
                                </label>
                            </form>

发送函数:

const handleSand = async (e) => {
        e.preventDefault();
        // const token = await recaptchaRef.current.executeAsync();

        if (file) {
            const formData = new FormData();
            formData.append('name', name);
            formData.append('telephone', telephone);
            formData.append('email', email);
            // formData.append('token', token);
            formData.append('message', message);
            formData.append('type', true);
            formData.append('file', file);

            axios
                .post('https://httpbin.org/anything', {
                    formData,

                    headers: {
                        'content-type': 'multipart/form-data',
                    },
                })
                .then((r) => {
                    setSent(true);
                    setMsg(r.data.message);
                    console.log(r);
                })
                .catch((e) => {
                    console.log(e);
                });
        }

返回对象:

{
    "data": {
        "args": {},
        "data": "{\"formData\":{},\"headers\":{\"content-type\":\"multipart/form-data\"}}",
        "files": {},
        "form": {},
        "headers": {
            "Accept": "application/json, text/plain, */*",
            "Accept-Encoding": "gzip, deflate, br",
            "Accept-Language": "en-US,en;q=0.9,pt-BR;q=0.8,pt;q=0.7",
            "Content-Length": "64",
            "Content-Type": "application/json;charset=UTF-8",
            "Host": "httpbin.org",
            "Origin": "http://localhost:3000",
            "Referer": "http://localhost:3000/",
            "Sec-Ch-Ua": "\" Not;A Brand\";v=\"99\", \"Google Chrome\";v=\"91\", \"Chromium\";v=\"91\"",
            "Sec-Ch-Ua-Mobile": "?1",
            "Sec-Fetch-Dest": "empty",
            "Sec-Fetch-Mode": "cors",
            "Sec-Fetch-Site": "cross-site",
            "User-Agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Mobile Safari/537.36",
            "X-Amzn-Trace-Id": "Root=1-60d617af-00a8c7552bbb6ad22e05124d"
        },
        "json": {
            "formData": {},
            "headers": {
                "content-type": "multipart/form-data"
            }
        },
        "method": "POST",
        "origin": "186.220.222.123",
        "url": "https://httpbin.org/anything"
    },
    "status": 200,
    "statusText": "",
    "headers": {
        "content-length": "1164",
        "content-type": "application/json"
    },
    "config": {
        "url": "https://httpbin.org/anything",
        "method": "post",
        "data": "{\"formData\":{},\"headers\":{\"content-type\":\"multipart/form-data\"}}",
        "headers": {
            "Accept": "application/json, text/plain, */*",
            "Content-Type": "application/json;charset=utf-8"
        },
        "transformRequest": [
            null
        ],
        "transformResponse": [
            null
        ],
        "timeout": 0,
        "xsrfCookieName": "XSRF-TOKEN",
        "xsrfHeaderName": "X-XSRF-TOKEN",
        "maxContentLength": -1,
        "maxBodyLength": -1
    },
    "request": {}
}

1 个答案:

答案 0 :(得分:0)

这是因为标题应该是 .post 函数的第三个参数。

axios.post(url, payload, config)

相关问题