Fetch Headers and POST Request
This note is for making fetch() requests with headers and POST data.
POST Request Example
async function createUser(){
const response = await fetch("https://example.com/users", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: "Yuwei",
role: "student"
})
});
if(!response.ok){
throw new Error("Request failed");
}
const data = await response.json();
console.log(data);
}Key Ideas
method: "POST"tells the server you are sending data.headersdescribe the request body format.JSON.stringify()converts a JS object into JSON text.await response.json()converts JSON response data back into a JS object.