【问题标题】:input FormData reactjs hooks输入 FormData reactjs 钩子
【发布时间】:2021-03-04 06:27:17
【问题描述】:

我正在学习 React js,这里我正在向数据库进行输入。这里我有一个问题,如何发送格式为 FormData(); 的数据;使用钩子?

const initialFormState = { id: null, id_user: '1', kode: '', qty: '', harga: '' }
  
    const [ibarang, setIbarang] = useState(initialFormState);

    const handleInputChange = (e) => {
        const { name, value } = e.target
        setIbarang({ ...ibarang, [name]: value })

    }

    const handleSubmitBarang = async (e) => {
        e.preventDefault()
        console.log(ibarang);
        try {
        let res = await Axios.post('https://API.COM', ibarang, {
            'Content-Type': 'application/x-www-form-urlencoded',
        })
        console.log(res.data)
        if (res.data.status === 200) {
            setTimeout(() => {
                // history.push("/dashboard")
            }, 500);
        } else if (res.data.status === 401) {
            setalertMessage("Username atau password salah!")
        } else {
            setalertMessage("Periksa kembali koneksi internet anda")
        }
    } catch (error) {
        setalertMessage("Periksa kembali koneksi internet anda")
    }

}

【问题讨论】:

  • 你想做什么?将数据发送到服务器?
  • 发布数据,因为后端使用form-data
  • 好吧,你可以使用任何你想将数据发送到服务器的包。我建议使用更简单的东西,比如 axios,来发送简单的 JSON 字符串。试一试。
  • 我已经更新了我上面的代码,我的意思是,如何使用 let FormData = require ('form-data');让数据 = 新的 FormData ();

标签: reactjs post axios


【解决方案1】:

首先,通过

添加axios NPM包
npm i axios

其次,尝试类似:

import axios from 'axios';

// Submit the form data 
axios.post('https://API.COM', 
  JSON.stringify(ibarang)
).then(response => {
  console.log('Submit Success')
}).catch(e => {
  console.log('Submit Fail')
});

【讨论】:

    猜你喜欢
    • 2020-08-04
    • 2020-10-23
    • 2015-02-22
    • 2020-12-14
    • 2020-08-04
    • 1970-01-01
    • 2019-11-21
    • 1970-01-01
    • 2020-04-26
    相关资源
    最近更新 更多