Search code examples
javascriptreactjsaxiosuse-form

Form submission React , axios , useForm


Using useForm need to create a form where, for example, 3 inputs, 2 types of text ('name' and 'email') and 1 file ('photo'). When the button is clicked, so the post is submitted, a POST request must be made to the URL via axios with a specific header ('Token').

The problem is that in data I have what is in the photo below (photo length: 0), so the request is not proceed.

            <form className='main__post-form' onSubmit={handleSubmit(onSubmit)}>
            <label> Name
                <input autoComplete='off'
                    {...register('name', {
                        required: true,
                    })}
                />
            </label>
            <label> Email
                <input autoComplete='off'
                    {...register('email', {
                        required: true,
                    })}
                />
            </label>
            <label> Picture
                <input type='file' accept='.jpg, .jpeg'
                       {...register('photo', {
                           required: true,
                       })}
                />
            </label>
           <button className='main__post-submit' type='submit'>Submit</button>
        </form>

so on submit:

const onSubmit = (data) => {
    axios.post('some url there', data, {
        headers: {
            'Token': token,
        }
        }).then((res) => {console.log('ok', res)}).catch((err) => {console.log('error', err)})
    reset()
}

enter image description here


Solution

  • Please add content type header in axios and try "Content-Type": "multipart/form-data"