Why does Axios default to sending my POST request with Content-Type application/x-www-form-urlencoded when passing a string as the request body?

While working with axios to make POST requests, I encountered an interesting behavior. I am passing URLs entered by the user to my Spring RestController, which accepts the request body as a String. The code snippet looks like this:

@PostMapping("user/{userId}/link")
public ResponseEntity<UserLinkDTO> addUserLink(
    @PathVariable(value = "userId") Integer userId, @RequestBody String url) {
    ...
}

On the front end, my axios request is structured as follows:

const saveUserLink = async (userId: number, url: string): Promise<UserLinkDTO> => {
  return axiosInstance.post(`user/${userId}/link`, url))
  .then(r => r.data)
);

When sending some random URLs (containing =) such as:

https://www.google.com/search?client=firefox

https://www.yahoo.com/somePage?key=value&hello=world

The Spring POST method receives the url exactly as it was sent.

However, when sending URLs without any =, like:

https://www.google.com

https://www.yahoo.com/somePage

The Spring POST method receives the url with an appended =. This results in the links being received as:

https://www.google.com=

https://www.yahoo.com/somePage=

I noticed that these requests are being sent with

Content-Type: application/x-www-form-urlencoded
instead of the expected application/json. According to the axios documentation, all requests should be serialized to JSON and sent with Content-Type: application/json. Interestingly, only this specific request is being converted to
Content-Type: application/x-www-form-urlencoded
.

To resolve this issue, I added custom headers to my axios post request to change the Content-Type back to application/json:

const saveUserLink = async (userId: number, url: string): Promise<UserLinkDTO> => {
  return axiosInstance.post(`user/${userId}/link`, url, {
    headers: {
      'Content-Type': 'application/json',
    }
  })
  .then(r => r.data)
);

As a result, my Spring POST method now successfully receives the URLs without any extra = appended, regardless of their content. This adjustment resolves the issue and ensures consistent handling of URLs by the API.

This experience raises the question: why does axios change the Content-Type from application/json to

application/x-www-form-urlencoded
when providing a string as the request body?

Answer №1

By default, axios uses 'application/x-www-form-urlencoded' as the content-type.

//Source: https://github.com/axios/axios/blob/master/lib/defaults.js
var DEFAULT_CONTENT_TYPE = {
  'Content-Type': 'application/x-www-form-urlencoded'
};

//...

utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
  defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);
});

However, when the request data is an Object, axios sets contentType to 'application/json':

    if (utils.isObject(data)) {
      setContentTypeIfUnset(headers, 'application/json;charset=utf-8');
      return JSON.stringify(data);
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Jackson's circular dependency arises solely from its depth and not from a combination of both depth and breadth

Let's consider two classes: User and Car. @Entity @Table(name = "User") @JsonIdentityInfo( generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") public class User { @Id @GeneratedValue(strategy= GenerationT ...

How can you keep TypeScript satisfied when extending classes that come from 'node modules'?

Update: Included ARTICLES_QUERY, tsconfig.json, and package.json as requested. Update 2: The current solution is functional, but it doesn't seem ideal. Any suggestions for improvement would be appreciated. export default class InterfaceGraphQLApi ex ...

A guide on updating CSS content dynamically within ExtJS

In my resource folder, I have a CSS file that contains some values which I need to change or add based on certain conditions. However, I'm struggling to figure out how to achieve this. Here is an example of the code: triggers: { clear: { ...

"React's ambiguous understanding of 'this' within a function

Can anyone help me understand why the value in the renderInput function is showing as undefined? I've checked the code and everything seems fine. Here is the error: Uncaught TypeError: Cannot read property 'renderError' of undefined This ...

The error code TS2554 is triggered when the function expects between 1 to 2 arguments, but receives

When attempting to include { useHash: true } in RouterModule.forRoot, I encountered the following error. How can I add additional arguments? @NgModule({ imports: [RouterModule.forRoot( appRoutes, { enableTracing: true }, // <-- for debugging ...

Is three too much for the Javascript switch statement to handle?

I'm a beginner in Javascript and am working on a project to create a fun program involving astrological signs, planets, and houses to generate a story. I have included three switch statements within one function to accomplish this. I'm encounter ...

Guide on extracting value from XML data using $.ajax and then displaying it within a $.each loop

As part of our study project, we have a task that involves comparing an array of strings with an XML database. My approach was to break it down into two parts since we need to perform the comparison function twice. First, I iterate through the array using ...

Click to toggle information using Jquery

I am attempting to create a button that, when clicked, will toggle between displaying temperature in Fahrenheit and Celsius. While I have been able to make it work initially, the toggle only occurs once and then stops. I have experimented with separate if ...

Managing AJAX Errors in PHPAJAX error handling tips for developers

My current code is only set up to display a general error message when an error occurs during execution. I want to improve it by returning specific error messages for different scenarios. However, I have not been able to find satisfactory solutions in my s ...

What are the benefits of integrating firebase-admin-sdk with firebase-ui and firebase-client-sdk for both server-side and client-side authentication management?

I am currently working on implementing an authentication mechanism for my Next.js project. Specifically, I plan to utilize firebase-auth and firestore. My main goal is to keep important security logic on the server side to ensure safety. I want to avoid ex ...

Tips for validating numeric fields that rely on each other with Yup

I am facing a challenge in setting up a complex validation using the library yup for a model with interdependent numeric fields. To illustrate, consider an object structured like this: { a: number, b: number } The validation I aim to achieve is ...

Enable swipe functionality for mobile users

Looking to make the code below swipable on mobile devices. Any suggestions or resources to achieve this would be greatly appreciated! <script> var links = document.querySelectorAll(".heart"); var wrapper = document.querySelector("# ...

Click on the HTML page to load an Array of Arrays containing strings

Earlier, I posted a topic about an issue with Observable loading on an HTML page: Observable need a click to load on html page. Unfortunately, I am still facing the same display problem where I have to click on the input field to display the content of a ...

jQuery request avoids encountering any 'Access-Control-Allow-Origin error

I am attempting to retrieve content from one website and transfer it to another website. Unfortunately, I keep encountering the error mentioned in the title during my jQuery request. Below is the code I am using: $.ajax({ url: 'destinationURL' ...

How to access JavaScript files from "bower_components" instead of "node_modules" using webpack

With the utilization of main-bower-files in my Gulp compilation tasks, it is not feasible for me to use webpack to require modules from the node_modules directory as it would interfere with the processing of CSS, images, and fonts in my current asset sys ...

"Redirecting using parameters upon pressing the enter key: A step-by-step guide

I've been pondering about the best way to redirect to a specific site while including query parameters in the URL. <input id="query" name="query" placeholder="Search" type="input" > I have experimented wi ...

Sharing data from ViewModel to JavaScript

Currently, in the process of creating an MVC 5 web application, I am faced with the challenge of passing a value from my ViewModel to a function in my JavaScript code. The objective is to hide a Label/Div element when the user selects the option "No" and ...

What are the steps to create fixed Angular Material Chips?

I'm currently attempting to achieve a similar look and functionality as demonstrated here: https://material.angularjs.org/1.1.9/demo/chips#static-chips where the chips are static and not selectable, clickable, or hoverable. However, I am utilizing Ang ...

Is there a way to transform an HTML canvas into a tangible photograph?

I am currently working on converting HTML content into a real image on the client's side. After conducting research on canvas2base64, canvas2base64, and html2base64 on Stack Overflow, I have found that the generated images are always based on base64 c ...

Information displayed when Tab is inactive - Material Ui and React

Just diving into the world of React and UI design, seeking some guidance on an issue I'm facing. I'm working on implementing Material Ui Tabs in my Component, but struggling to get a tooltip to show on a disabled Tab. Here's a snippet of my ...