[JavaScript] Sending JavaScript Objects to the Server with fetch()
Sending JavaScript Objects to the Server with fetch()
GET with query parameters
This works well for small values:
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.
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
Post a Comment