[JavaScript] Sending JavaScript Objects to the Server with fetch()

 Sending JavaScript Objects to the Server with fetch()

When sending requests to the server in JavaScript, fetch() is the most commonly used method. For simple data, it’s easy to add query parameters directly in the URL. But when sending structured data like an object, a different approach is required.

GET with query parameters

This works well for small values:

fetch('/blog/add_game/?title=Zelda&platform=Switch')

It’s readable and efficient when only sending a few flat fields like strings or numbers.

POST with JSON for structured data

When sending an entire object, the recommended pattern is to use POST and send the object as JSON.

fetch('/blog/add_game/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(game)
})

This tells the server that the body contains JSON, not form data or plain text.

Why Content-Type is required

Without the Content-Type header, the server doesn’t know how to parse the body. For example:

  • In Flask, request.get_json() would return None

  • In FastAPI, the request body might be ignored or throw a validation error

Always include Content-Type: application/json when sending JSON via fetch(). It ensures the server can properly deserialize the incoming request.

Avoid encoding objects in the URL

While it’s technically possible to serialize a full object and attach it to a query string using encodeURIComponent(JSON.stringify(game)), this quickly becomes messy and error-prone. It also risks hitting URL length limits.


Comments