How to Fix AxiosError: Request Failed With Status Code 400

An AxiosError with HTTP status 400 Bad Request means a server or intermediary rejected your request as invalid. Start by reading the response body, then check the endpoint’s required parameters, authentication, and body format, not by reinstalling Axios. The same message can also appear in an application’s email settings or file uploader, where the underlying problem is outside your JavaScript.

Use the symptoms below to narrow down the investigation.

Symptom Likely Cause What to Check First
The response names a missing or invalid field Request validation failed Field names, types, formats, and allowed values
The backend receives an empty or unexpected body Incorrect Axios arguments or incompatible body parsing Where the payload is passed and which content type the endpoint accepts
Only file uploads fail Multipart formatting, field validation, or upload restrictions Form fields, multipart boundary, backend parser, and file requirements
The response is an HTML error page rather than API JSON A proxy, gateway, or web server may have rejected the request Response headers and intermediary logs
The request works in an API client but not in your app The actual requests differ URL, credentials, headers, cookies, and serialized body
Uploads fail only in a multi-instance deployment Session routing may be inconsistent Whether upload requests reach the instance holding the user’s session

What an Axios Bad Request Error Means

Axios normally rejects its promise when it receives an unsuccessful HTTP response. The error message describes that response; it does not identify which field, header, or server component caused it.

The most useful properties are:

  • error.response.status: the HTTP response status.
  • error.response.data: the response body, which may contain validation details.
  • error.response.headers: response headers that can help identify the responding service or a request identifier.

If error.response exists, Axios received a response. If only error.request exists, a request was made but no response was available to Axios; investigate that as a different problem rather than assuming a Bad Request response.

Also distinguish Axios’s own error.code, such as ERR_BAD_REQUEST, from the HTTP status. Use error.response.status to determine what the server returned.

A client-error response does not prove your frontend code is wrong. An outdated API contract, incorrect backend validation, missing body parser, or reverse-proxy configuration can also be responsible.

How to Fix an Axios Bad Request Error

Inspect the response, verify the endpoint contract and credentials, then correct the Axios arguments and payload format.

Step 1: Read the Response Body

  1. Open your browser’s developer tools and select Network.
  2. Reproduce the failure and select the failed request.
  3. Inspect its response body, request URL, method, headers, and submitted payload.
  4. Capture the useful error details in your catch handler.

For local debugging with non-sensitive test data, use this pattern. Here, requestConfig represents the configuration object for your existing Axios request, including its URL, method, headers, and data.

import axios from "axios";
try {
  const response = await axios.request(requestConfig);
  // Handle response.data here.
} catch (error) {
  if (!axios.isAxiosError(error)) {
    throw error;
  }
  if (error.response) {
    console.error("HTTP status:", error.response.status);
    console.error("Response body:", error.response.data);
  } else if (error.request) {
    console.error("No response available:", error.message);
  } else {
    console.error("Request setup failed:", error.message);
  }
}

Look for a field-level explanation such as “email is required,” “invalid date format,” or “unsupported content type.” The body may be JSON, plain text, or HTML, so do not assume it always has a message property.

Avoid dumping the entire Axios error or configuration into production logs. It can contain authorization headers, cookies, personal information, or submitted secrets. Redact those values before sharing diagnostic output.

Step 2: Check the Endpoint’s Contract and Credentials

  1. Confirm the final request URL and HTTP method against the API documentation.
  2. Check the required authentication mechanism before changing serialization.
  3. Compare every parameter with the API’s required location, name, type, and format.
  4. Check validation rules for the submitted values, not just whether the fields exist.

An endpoint can reject a present but incorrectly formatted parameter, invalid authentication credentials, or a value that fails server-side validation. Sending every required field is therefore not enough.

For each field, ask:

  • Does it belong in the URL path, query string, body, or a header?
  • Is its capitalization correct?
  • Does the API expect a number, string, boolean, object, or array?
  • Does it accept an empty string or null?
  • Does it require a particular date format, enumeration value, or identifier syntax?
  • Are there relationships between fields, such as an end date having to follow a start date?

HTML form values commonly arrive in JavaScript as strings. If an API requires a numeric value, convert and validate it deliberately; do not assume the backend will coerce it.

For authentication, verify that the required credential is actually present and current. Check for accidental values such as Bearer undefined, an expired token, an incorrect API-key header, or a missing session cookie. Although authentication failures often use other status codes, some endpoints return Bad Request.

Step 3: Correct the Axios Arguments and Body Format

  1. Make sure request data and Axios configuration occupy the correct argument positions.
  2. Match the payload encoding to the endpoint’s accepted content type.
  3. Inspect the transmitted payload after making the change.

For axios.post, the arguments are the URL, request body, and optional configuration object.

This example assumes an API that accepts a JSON object containing an email field. The endpoint is illustrative; replace it with your own.

const response = await axios.post(
  "/api/users",
  { email: "[email protected]" },
  { headers: { Accept: "application/json" } }
);

With its standard configuration, Axios serializes a plain JavaScript object as JSON. You generally do not need to call JSON.stringify yourself.

A frequent mistake is putting configuration inside the body:

// Incorrect if the API expects email at the top level:
await axios.post("/api/users", {
  headers: { Accept: "application/json" },
  data: { email: "[email protected]" }
});

That sends an object containing headers and data as application data. It does not set a request header or unwrap the nested email field.

For a GET request, query parameters belong in the configuration object’s params property:

const response = await axios.get("/api/search", {
  params: { query: "axios error" }
});

Using params also avoids hand-building a query string with unescaped user input. However, arrays and nested objects still need the serialization format your API expects.

Keep these distinctions clear:

  • Content-Type describes the body you are sending.
  • Accept describes the response formats you can accept.
  • Declaring a body to be JSON does not make non-JSON content valid JSON.
  • Manually serializing JSON is not inherently wrong, but serializing an already serialized value can change an object into a JSON string.

Inspect the actual outgoing request rather than judging only the source code. Shared Axios defaults, request interceptors, and transformation functions can change the payload or headers.

Step 4: Compare the Failing Request With a Known-Good Request

  1. Reproduce the request in an API request client using non-sensitive test data.
  2. Match the method, URL, query parameters, body encoding, and authentication.
  3. Compare the requests field by field.
  4. Change only the difference supported by the evidence.

If your API client succeeds, do not immediately conclude that Axios is broken. The client may be adding an authorization header automatically, using a different environment URL, or sending a different body format.

Pay particular attention to:

  • A base URL combined with an unexpected relative path.
  • Query parameters encoded differently.
  • Missing cookies or headers.
  • Extra object nesting.
  • Empty fields that one client omits and another sends.
  • A JSON header inherited by a request that should be multipart.

If both requests fail, investigate the API contract and server-side handling. That result makes a React-specific or Axios-specific explanation less likely.

For requests that create, charge, send, or delete something, use a test environment or test resource. Replaying a request can have side effects even when the client did not receive the response it expected.

Step 5: Fix the Rejecting Layer and Retest

  1. Match the failed request to backend or proxy logs using its timestamp or request identifier.
  2. Determine which component rejected it.
  3. Apply the narrowest correction.
  4. Submit the corrected request and verify the intended operation completed.

If the request reaches the application, inspect its parsing and validation errors. For example, a JSON parser needs to run before a route that reads a JSON body; a multipart upload needs compatible multipart handling.

If the application has no record of the request, inspect the reverse proxy, API gateway, or web server. An HTML error page can help identify that layer, but the response format alone is not proof.

Correct the request when it violates the documented contract. Correct the backend when its implementation contradicts that contract. Do not loosen validation merely to make an unexplained error disappear.

Finish by checking both the response and the application state: the record was created, the file was processed, or the intended operation otherwise completed.

Multipart and XML Request Problems

Multipart File Uploads

A multipart upload succeeds only when the endpoint accepts multipart data and the submitted fields pass its validation rules.

For a browser upload, create a FormData object and append the fields the endpoint requires. In this example, file is a browser File, description is a string, and uploadUrl is your endpoint; the field names must match its contract.

const form = new FormData();
form.append("file", file);
form.append("description", description);
const response = await axios.post(uploadUrl, form);

Let the browser and Axios manage the multipart content type and boundary. Do not manually supply a bare multipart header without its boundary, and check that a shared JSON content-type default is not interfering with this request.

The backend must also accept and parse multipart form data. A route configured only for JSON cannot interpret an upload as though it were a JSON object.

Check the remaining upload requirements:

  • The file field name matches the backend’s expected name.
  • Required text fields are included.
  • File type and size meet the application’s restrictions.
  • Values appended as text satisfy the backend’s validation rules.

If size seems relevant, test with a smaller valid file. Treat that as a diagnostic comparison: not proof that changing an Axios setting will fix a server-side limit.

After correcting the format or parser, upload a valid test file and confirm the application can retrieve or process it.

XML Request Bodies

If the endpoint expects XML, send valid XML with the media type that endpoint specifies. Do not send a JavaScript object and assume that an XML header will convert it.

For an endpoint documented to accept application/xml, the request can take this form:

const response = await axios.post(endpoint, xmlBody, {
  headers: { "Content-Type": "application/xml" }
});

Here, xmlBody must already contain the XML document. Check its root element, required elements, namespaces, encoding, and escaped text against the API’s schema.

The correct media type can differ between XML-based APIs, so use the endpoint’s documented contract rather than treating this example as universal.

Resubmit the corrected document and check the application-level result. Some XML APIs return an error document even when the transport request itself succeeds.

When the Error Comes From an App or Deployment

Check server-side email settings or session routing, then confirm delivery or uploaded-file access after the correction.

Email Settings Fail Without Any Axios Code to Edit

If you see this message in an application’s administration interface, Axios may simply be the frontend library displaying a backend failure.

For Nextcloud email tests, community troubleshooting points to an unset or invalid email address on the signed-in administrator’s account, along with SMTP configuration and authentication problems.

Check that the account has a valid recipient address for the test. Then verify the configured SMTP host, authentication, sender address, and encryption requirements against your email provider’s settings.

Use the server-side mail error to identify the actual rejection. Avoid replacing email settings with unrelated examples.

Run the email test again and verify delivery to the intended inbox. A changed browser message alone does not establish that mail delivery works.

Uploads Fail Only After Deployment

In multi-instance Streamlit deployments, community troubleshooting has identified uploads reaching a different instance from the one holding the browser’s WebSocket session.

If uploads work locally but fail behind a load balancer, inspect where the WebSocket connection and upload request are routed. When they reach different instances and the upload depends on instance-local session state, configure session affinity at the hosting or load-balancing layer.

Do not disable CORS or cross-site request forgery protections as a general-purpose repair. Those changes do not establish that session routing is correct.

After correcting routing, test uploads from both an existing browser session and a fresh session. Confirm that the application can read the uploaded file, not merely that the upload request stops showing an error.

How to Confirm the Fix and Prevent Regressions

A working fix should survive more than one successful request. Verify these conditions before closing the issue:

  • The operation completed: The API returned the expected success status and any response body promised by its contract.
  • The normal application path works: The request succeeds from the actual form, component, or upload interface, not just a standalone client.
  • Invalid input produces a useful error: Missing fields and invalid values return actionable validation details rather than an unexplained failure.
  • Authentication still behaves correctly: Valid credentials work, and invalid credentials do not bypass checks.
  • Temporary diagnostics are removed or redacted: Logs do not expose tokens, cookies, or sensitive payloads.

Add a regression test around the specific mismatch you corrected. If the problem was a string sent instead of a number, test that conversion. If it was an upload field name, test the expected multipart fields. If the backend returned no useful detail, improve its validation response without exposing internal implementation details.

If the failure remains, prepare a minimal reproduction containing the request method, URL structure, body shape, response body, and matching server log entry. That gives the API maintainer something concrete to investigate instead of only the Axios error message.

Frequently Asked Questions

Why Does Axios Show “Uncaught (in Promise)”?

“Uncaught (in Promise)” means a rejected promise was not handled. Use await inside a try/catch, or attach a .catch() handler to the promise. A synchronous try/catch around an Axios call without awaiting it will not catch the later rejection.

Does validateStatus Fix a Bad Request?

No. Axios’s validateStatus option changes which HTTP responses resolve or reject the promise; it does not change the server’s response or repair the request. If you intentionally accept an error status, your application must still handle it as an unsuccessful operation.

What Does a $ in a Bad Parameter Error Mean?

A $ is not a standardized Axios error indicator; its meaning comes from the API or validator that produced the message. It may identify the document root in a validation path, or it may belong to a literal query parameter such as an OData parameter. Read the complete error and endpoint schema before adding, removing, or renaming a field.