【问题标题】:Trying to post data using axios and formData but it's empty尝试使用 axios 和 formData 发布数据,但它是空的
【发布时间】:2021-05-26 17:00:13
【问题描述】:

我正在使用 Vue3 和 axios 使用 FormData 发布表单,但它是空的,没有任何内容传递。

{"formData":{}}

这是我正在做的事情:

const formData= new FormData();
formData.set("name", name);

axios.post("postform",  formData);

我也试过这个:

formData.set("name", "John Doe");
axios.post("postform",  formData);

还有这个:

formData.append("name", "John Doe");
axios.post("postform",  formData);

但没有成功。没有错误,只是空的。

我在 PHP 中这样检索它们:

 echo $request->input("name");

所以我的问题是:

如何使用FormData发布数据?

【问题讨论】:

  • 尝试在 php 中添加 print_r($_REQUEST) 而不是 echo $request->input("name"); 看看会显示什么
  • 谢谢。它是空的。它显示了一个空的 formData 数组。
  • 你在后端使用 laravel @ThiagoGuimarães 吗?

标签: javascript vue.js axios form-data


【解决方案1】:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import Footer from './Footer';
import Header from './Header';
import Map1 from './img/google-map.png';
import Map2 from './img/google-map-2.png';

const Forms = () => {
   
  const [name, setCompanyName] = useState('')
  const [address, setAddress] = useState('')
  const [phone, setContact] = useState('')
  const [company_logo, setLogo] = useState('')
  const [website, setWebsite] = useState('');
  const [faceBook, setFacebookUrl] = useState('');
  const [instagram, setInstagramUrl] = useState('');
  const [twitter, setTwitterUrl] = useState('');
  const [location, setLocation] = useState('');
  const [city, setCity] = useState('');
  const [google_map_location, setGoogleLocation] = useState('');
  const [momo_number, setMomoNumber] = useState('')
  const [account_type,setAccount] = useState('');
  const [industry_uuid, setIndustry] = useState('');
  const [momo_acct_name, setMomoName] = useState('');
  const [background, setBackground] = useState('');
  const [country_uuid, setCountryId] = useState(null);
  const [accountList, setAccountList] = useState(null);
  const [industryList, setIndustryList]=useState(null);
  const [gps, setGps] = useState('');
  const [token, setToken]=useState(null);


  useEffect(() => {
      

    axios.get('https://rosmallonline.com:7070/ecoms-api/setup/get_countries/')
      .then(res => {
        console.log(res.data.country[0].country_id);
        const countryid = res.data.country[0].country_id;
        setCountryId(countryid);
      })
      .catch(console.log)
    
      axios.get('https://rosmallonline.com:7070/ecoms-api/setup/get_industries/')
      .then(res2 => {
        console.log(res2.data);
        setIndustryList(res2.data.industries);
      })
      .catch(console.log)
  
      axios.get('https://rosmallonline.com:7070/ecoms-api/setup/get_account_types/')
      .then(res3 => {
        console.log(res3.data);
        setAccountList(res3.data.account_types);
      })
      .catch(console.log)

      setToken(sessionStorage.getItem('token'));
  },[])




  const  submitHandler = async (e) => {
    e.preventDefault();

    const formData = new FormData();
    formData.append('file', company_logo, 'company_logo');
    formData.append('name', name);
    formData.append('address', address);
    formData.append('phone', phone);
    formData.append('industry_uuid', industry_uuid);
    formData.append('country_uuid', country_uuid);
    formData.append('account_type', account_type);
    formData.append('city', city);
    formData.append('social_media',{
      'faceBook':faceBook,
      'instagram':instagram,
      'twitter':twitter
    });
    formData.append('background', background);
    formData.append('location', location);
    formData.append('website', website);
    formData.append('gps', gps);
    formData.append('google_map_location', google_map_location);
    formData.append('momo_number', momo_number);
    formData.append('momo_acct_name', momo_acct_name);

   
    await axios.post('ecoms-api/company/update_company_profile/', 
      formData
    ,{
      headers: {
        'Content-Type': 'multipart/form-data',
        'X-COMPANY-USER-AUTH': token
     }
    }).then(response => {
      console.log(response);
      if(response.data.status === 200){
        alert(response.data.message)
    } else {
        alert(response.data.message)
    }
    });
           
  }


        return (
            <div className="page">
        
      </div>

        );
    }


export default Forms;

【讨论】:

    【解决方案2】:

    如果您没有发送任何文件(或者您的表单不是 maltipart/form-data),您可以使用以下方法通过 axios 发送数据:

    let formData = {};
    formData.name =  "John Doe";
    axios({
      url: "postform",
      method: "POST",
      data: formData
    });
    

    编辑:

    如果您要发送任何文件,那么在我的情况下,以下对我有用:

    
    const formData = new FormData();
    formData.append("name", "hello world");
    
    
    
    axios({
        url: 'postform',
        method: "POST",
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
    })
    

    【讨论】:

    • 谢谢,但我需要发送文件。
    • @ThiagoGuimarães 我已经编辑了答案,请检查
    • 不起作用,但谢谢。它说 getHeaders 在 formData 类型上不存在
    • @ThiagoGuimarães 我已经在标题中编辑了答案(添加了'Content-Type': 'multipart/form-data')。试试看
    • 谢谢,但实际上是我的错。我在 axios 中的 {} 中有 formData。但我赞成你的回答,因为你花时间。再次感谢您
    【解决方案3】:

    您可以将 FormData 对象转换为简单对象,然后将该对象发送到服务器。

    const formData = new FormData();
    formData.set("key1", "value1");
    formData.set("key2", "value2");
    
    let data = {};
    
    // convert the key/value pairs
    for(var pair of formData.entries()) {
        data[pair[0]] = pair[1];
    }
    
    axios.post("postform",  data);
    

    【讨论】:

    • 谢谢。我会投票,因为我可以看到这些值,但是在尝试将值传递给键时仍然遇到一些错误。 Type 'FormDataEntryValue' is not assignable to type 'string'
    • FormData 条目值可以是字符串、null 或 File。试试formData.get('foobar').toString()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-22
    • 2021-09-01
    • 1970-01-01
    • 2018-02-26
    • 2021-05-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多