Menu

Sending data

“Query strings, HTML forms and JSON bodies.”

View .md

There are three common ways to send data to a server.

1. In the URL: query strings#

Good for filters, search terms and pagination on GET requests:

http
GET /products?category=books&sort=price&page=2 HTTP/1.1
Host: shop.example.com

Warning

URLs end up in browser history, server logs and analytics. Never put passwords or tokens in a query string.

2. In the body: HTML forms#

A plain HTML form sends its fields in the body, encoded like a query string:

login.htmlhtml
1<form method="post" action="/login">
2  <input name="email" type="email">
3  <input name="password" type="password">
4  <button>Log in</button>
5</form>

Submitting it sends:

http
1POST /login HTTP/1.1
2Host: example.com
3Content-Type: application/x-www-form-urlencoded
4Content-Length: 41
5
6email=amin%40example.com&password=hunter2

For file uploads, the form uses enctype="multipart/form-data", which splits the body into parts so binary files fit.

3. In the body: JSON#

APIs usually send JSON. The Content-Type header tells the server how to read the body:

http
1POST /api/todos HTTP/1.1
2Host: api.example.com
3Content-Type: application/json
4Content-Length: 43
5
6{"title": "Learn HTTP", "completed": false}

From the terminal:

bash
curl -X POST https://httpbin.org/post \
  -H "Content-Type: application/json" \
  -d '{"title": "Learn HTTP", "completed": false}'

From JavaScript:

create-todo.jsjs
1const res = await fetch("/api/todos", {
2  method: "POST",
3  headers: { "Content-Type": "application/json" },
4  body: JSON.stringify({ title: "Learn HTTP", completed: false }),
5});

Which one when?#

You want to…Use
Filter or search, shareable as a linkQuery string on GET
Submit a simple HTML formapplication/x-www-form-urlencoded
Upload filesmultipart/form-data
Talk to an APIapplication/json

Byte check

0/3

Answer these 3 questions to commit this byte to your learning path.

  1. Where should the search term for a shareable results page go?
  2. Why should a password never go in a query string?
  3. Which Content-Type does a form use to upload files?
Search posts and bytes

Optional account

Keep your progress everywhere

Everything on AminBytes is free to read, with or without an account. Sign in only if you want your commits, streak and merged topics saved, on every device.

or

We keep only your name, avatar and which bytes you finished, and you can delete it all anytime. Privacy