Published on

Fix AxiosError: Request failed with status code 400 in React

Authors
  • Name
    Ripal & Zalak
    Twitter

Fix AxiosError: Request failed with status code 400 in React.js

Introduction

If you're working with React.js and Axios to send HTTP requests, you might encounter this error:

AxiosError {message: 'Request failed with status code 400', name: 'AxiosError', code: 'ERR_BAD_REQUEST'}

This error typically means your request is malformed or missing required fields. In this guide, we'll go over common reasons for this issue and how to fix them.


Common Causes & Solutions

1️⃣ Sending Data Incorrectly

Problem: Axios expects an object, but you might be sending a string.

Solution: Remove JSON.stringify() and send the object directly.

Incorrect Code:

const handleSubmit = async (event) => {
  event.preventDefault()
  try {
    const data = await CommentsAPI.create(JSON.stringify(comment)) // ❌ Wrong: Sending as a string
    console.log(data)
  } catch (error) {
    console.log(error)
  }
}

Correct Code:

const handleSubmit = async (event) => {
  event.preventDefault()
  try {
    const response = await CommentsAPI.create(comment) // ✅ Correct: Sending object directly
    console.log(response.data)
  } catch (error) {
    console.error(error.response ? error.response.data : error.message)
  }
}

2️⃣ Incorrect API Payload Format

Problem: The API expects a different JSON structure.

Solution: Wrap your data in a data object if required.

Incorrect:

await CommentsAPI.create({ pseudo: 'John', content: 'Hello' })

Correct (if API requires data wrapper):

await CommentsAPI.create({ data: { pseudo: 'John', content: 'Hello' } })

3️⃣ Missing Headers

Problem: The API requires Content-Type headers.

Solution: Add headers to your Axios request.

function create(comment) {
  return axios.post(URL_COMMENTS, comment, {
    headers: { 'Content-Type': 'application/json' },
  })
}

4️⃣ Incorrect API URL

Problem: Missing http:// or https:// in the API URL.

Solution: Ensure the API URL is correct.

Incorrect:

const URL_COMMENTS = 'localhost:5000/api/comments' // ❌ Missing http

Correct:

const URL_COMMENTS = 'http://localhost:5000/api/comments' // ✅ Correct URL

5️⃣ API Permissions Issue

If using Strapi or another CMS, ensure API permissions allow public POST requests:

✔ Go to Strapi Admin PanelSettingsRoles & PermissionsPublic ✔ Enable POST method for your API.


Final Debugging Steps

Log API response errors: console.error(error.response?.data || error.message);Test with Postman: Verify if the API works manually. ✔ Check CORS issues: Ensure backend allows requests from your frontend. ✔ Use a proxy in package.json:

"proxy": "http://localhost:5000"

Conclusion

A 400 Bad Request error usually means your request is incorrect or missing required data. Follow the steps above to debug and resolve it effectively.


FAQs

1. How do I fix Axios 400 error in React?

Ensure you send the correct JSON payload, include necessary headers, and check the API endpoint and permissions.

2. How do I debug Axios errors?

Use console.error(error.response?.data || error.message); to print detailed API errors.

3. Can CORS cause a 400 error?

Yes, if your API blocks requests from different origins. Use proper CORS settings on the backend or configure a proxy in React.