You can use a POST request to create a resource. Once the server gets your request, it updates a database that stores your information. Examples of POST requests include:
- Creating a user
- Creating an article
- Creating a comment
- Creating a todo item
POST requests require authentication. This means the server wants to make sure you are what it thinks you are. If you are not who it thinks you are, you cannot create a resource.
Authentication is an important process. If your bank doesnโt perform authentication, anyone can transfer money from your account into their account without your knowledge. Thatโs why requests need to be authenticated.
Weโll discuss authentication in a later lesson. For now, weโll send our requests to a fake server thatโs built for learning.
This server is called Typicode. The root endpoint you should use is https://jsonplaceholder.typicode.com.
Formatting your request body
Before you make a post request, you need to tell the server what data you are going to send over. When you make API calls, youโll usually send one of these formats:
- JSON
x-www-form-urlencoded
Formatting your request body as JSON
To tell a server youโre going to send JSON data, you need to set the Content-Type header to application/json.
To set the header in XHR, you can use setRequestHeader. This header must be set between the open and send calls.
const request = new XMLHttpRequest()request.addEventListener('load', e => { /* Do something */})request.open('method', 'link')request.setRequestHeader('Content-Type', 'application/json')request.send()To set the header in Fetch, you pass pass an object as the second argument. This object should contain a headers property.
fetch('some-url', { headers: { 'Content-Type': 'application/json', },})Note: headers are case insensitive. You can set Content-Type or content-type. Both will work.
Before sending your request, you also need to format your body as JSON. You can use JSON.stringify to do so.
To send the body with XHR, you pass it into the send call.
const body = JSON.stringify({ key: 'value' })request.send(body)To send the body with Fetch, you set the body property.
fetch('some-url', { headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ key: 'value', }),})Formatting your body as x-www-form-urlencoded
x-www-form-urlencoded data is data that can be sent as a URL. Query parameters are an example of url encoded data. They look like this:
param1=value1¶m2=value2If you need to send values that contain special characters (like slashes or spaces), you need to encode them such that they can be read through the url.
To do so, you use encodeURIComponent.
const encoded = encodeURIComponent('http://google.com')console.log(encoded) // http%3A%2F%2Fgoogle.comTo tell a server youโre going to send url encoded data, you set Content-Type to x-www-form-urlencoded.
// Sending url encoded data with XHRrequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')request.send('param1=value1¶m2=http%3A%2F%2Fgoogle.com')// Sending url encoded data with Fetchfetch('some-url', { headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: 'param1=value1¶m2=http%3A%2F%2Fgoogle.com',})Sending a post request
You need to set the method to post to send a POST request. You can do this when you call open with XHR.
request.open('post', 'some-url')You can set the method as a property of the second argument in Fetch:
fetch('some-url', { method: 'post',})Try sending a POST request to the Typicode. Hereโs an example:
fetch('https://jsonplaceholder.typicode.com/posts', { method: 'post', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title: 'This is my first article',status: published body: 'A shameless plug about myself' })}) .then(r => r.json()) .then(d => console.log(d))The server will let you know if your request succeeds. If it succeeds, it will send you one of the two responses:
- A success message
- A response that contains information about the created resource (like in the image below)
Note: This resource isnโt created on Typicode. Theyโre faked as if they were created.
Sending put or patch request
PUT and PATCH requests are used to update a resource on the server. They also require authentication. To send a PUT or Patch method, you set the method to put or patch.
When you send a PUT or Patch request, you also need to tell the server what resource you want to update or delete. This is often done through the path.
Hereโs an example where we update the 50th post with Fetch
fetch('https://jsonplaceholder.typicode.com/posts/50', { method: 'put', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title: 'This is my 50th article',status: published body: 'A poem about how JavaScript can save lives' })}) .then(r => r.json()) .then(d => console.log(d))Sending a delete request
To send a delete request, you use the delete method. You also need to tell the server what resource you want to delete.
fetch('https://jsonplaceholder.typicode.com/posts/1', { method: 'delete',})Exercise
Send the following requests to Typicode. Hereโs a link to the documentation if you need it.
- Send a GET Request to Typicode to request for the 56th post
- Send a POST request to create a post
- Do this with XHR
- Do this with Fetch
- Send a PUT request to change the 23rd post
- Do this with XHR
- Do this with Fetch
- Delete the 90th post
Welcome! Unfortunately, you donโt have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson