merlin
merlin

Reputation: 307

I get the error 'Request failed with status code 400' when I use axios

I am trying to create a register action using axios. When I submit, I get the error Request failed with status code 400. I don't know what i'm doing wrongly. Can anyone help

This is my action code:

export const userRegister = (
  firstName,
  lastName,
  phone,
  email,
  password,
  role,
  username
) => {
  return async (dispatch) => {
    const config = {
      headers: {
        'Content-Type': 'application/json',
      },
    }

    try {
      const res = await axios.post(
        `http://localhost:8000/api/v1/register`,
        { firstName, lastName, phone, email, password, role, username },
        config
      )
      console.log(res)
      // localStorage.setItem('token', res.data.token)

      dispatch({
        type: REGISTER_SUCCESS,
         payload: {
           successMessage: res.data.message,
           token: res.data.token,
         },
      })
    } catch (error) {
      console.log(error.response)
      dispatch({
        type: REGISTER_FAIL,
        payload: {
          error: error.response.data,
        },
      })
    }
  }
}

I get the error

Error: Request failed with status code 400
    at createError (createError.js:16:1)

My register code is this:

const handleSubmit = async (e) => {
    e.preventDefault()
      dispatch(
        userRegister(
          firstName,
          lastName,
          phone,
          email,
          password,
          role,
          username
        )
  }

WHat am i doing wrong?

Upvotes: 2

Views: 9551

Answers (1)

J2R
J2R

Reputation: 168

What I would suggest to have a look on is the following:

How does the API expect the data to be delivered?

Commonly, it's either Form Data or JSON body. As far as I understand here, you need to send the request body in JSON format, not a Form Data. Such misunderstanding often leads to error 400 Bad Request, so most probably you send the data in a wrong way to the API

May be you could try:

const res = await axios.post(
        `http://localhost:8000/api/v1/register`,
        {
          firstName: firstName,
          lastName: lastName,
          ...
        },
        config
      )

*/ This is a cleaner way to send a JSON body

Reference: https://masteringjs.io/tutorials/axios/post

If the API needs to process Form Data, change the config property from application/json to Content-Type:'multipart/form-data' and send Form data using the new FormData() constructor

Upvotes: 1

Related Questions