Client for the application in Redux
In the previous lessons we have almost completed the work with the server part for our application, we will add a little to it as needed in the following lessons. Now we need to create a client for the application that will send HTTP requests to the server.
Let's open our product app and create a file client.js
in the api
folder. First, we'll write the client
function itself, which will work for both GET and POST requests. It will receive the path, type, and body of the request (in the case of POST), if any, as parameters:
export async function client(url, method, body = {}) {}
Next, we need to create a options
object, in which we will pass various information for the request. This will be the request type and headers:
export async function client(url, method, body = {}) {
const options = {
method: method,
headers: {
'Content-Type': 'application/json',
},
}
}
The body
property is optional for us, we must pass it if we have a POST request. To do this, inside client
after the code for the options
object, we add it to options
with the request body in JSON format if the POST method is selected:
if (method === 'POST') {
options.body = JSON.stringify(body)
}
Then below in the client
code we organize the try
block, in the first line of which we get the response from the server using fetch
. In case of failure, we traditionally return a promise with an error:
let data
try {
const response = await window.fetch(url, options)
} catch (err) {
return Promise.reject(err.message ? err.message : data)
}
Now let's finish writing the code in the try
block. After receiving response
, we need to process it. We'll extract the data from it into JSON and if the response status signals us that everything is OK, then we'll return an object with data and information: status, headers, and address. If the status is not 'ok'
, then we'll throw an exception with the status text:
try {
const response = await window.fetch(url, options)
data = await response.json()
if (response.ok) {
return {
status: response.status,
headers: response.headers,
url: response.url,
data,
}
}
throw new Error(response.statusText)
}
We have the code for the client
function ready, all that's left is to write how our GET and POST methods will work when called. Let's write the code for them after the client
function. The client.get
method will take a path as a parameter and call the client
function, passing it this path and the GET request type:
client.get = (url) => client(url, 'GET')
And client.post
must pass to client
the path, the POST request type, and the request body:
client.post = (url, body) => client(url, 'POST', body)
That's all, our little client is ready to work with the server.
Open your application with students, create a file api
in it in the folder api
. After reviewing the lesson materials, write (copy) the code of the function client
and its two methods client.get
and client.post
.