Sending Data to a Server

await ez.request.post(url, {name: 'Rex', kind: 'dog'})

ez.request.post(url, data) sends data to the server at url. It returns the server's answer in the same shape as ez.request.get.

async function addPet() {
  let result = await ez.request.post(url, {name: 'Rex', kind: 'dog'})
  console.log(result)
  // {
  //   ok: true,
  //   status: 200,
  //   body: {id: 'a81f3c2e…', name: 'Rex', kind: 'dog'},
  //   error: null
  // }
}

What body holds depends on the server. Like get, post needs await, inside an async function.

The Server Can Say No

If the server doesn't accept the data, ok is false and status says why, for example 400 for data in the wrong shape:

let result = await ez.request.post(url, {name: 'Rex'})
console.log(result)
// {
//   ok: false,
//   status: 400,
//   body: {error: 'Schema validation failed', …},
//   error: 'Request failed with status 400.'
// }

So check result.ok before you use result.body.

Send the Value, Not the Input

let nameInput = ez.dom.select('#name').at(0)

await ez.request.post(url, {name: nameInput.value})  // correct: the text
await ez.request.post(url, {name: nameInput})        // wrong: the whole element
Lessons 0/5
▸ View all lessons Start lesson 1 →