Improving our fetch plugin

Currently, our $fetch method can only make GET requests to the server. It was enough for loading the FAQ, but now we need to add more features to it:

  1. In the plugins/fetch.js file, edit the signature of the function to accept a new options parameter:
      export async function $fetch (url, options) {
// ...
}

The options argument is an optional object for the browser's fetch method that will allow us to change different parameters, such as the HTTP method used, the request body, and more.

  1. At the beginning of the $fetch function, we would like to put some default values for this options parameter:
      const finalOptions = Object.assign({}, {
headers: {
'Content-Type': 'application/json',
},
credentials: 'include',
}, options)

The default options tell the server we will always send JSON in the request body, and tell the browser that we will also include the authorization token necessary to authenticate the user if they are logged in. Then, the provided options argument, if any, add its value to the finalOptions object (for example, the method property or the body property).

  1. Next, we add the new options to the fetch browser method:
      const response = await fetch(`${baseUrl}${url}`, finalOptions)
  1. Also, the server will always send errors as text, so we can catch them and display them to the user:
      if (response.ok) {
const data = await response.json()
return data
} else {
const message = await response.text()
const error = new Error(message)
error.response = response
throw error
}

We are now ready to make our first POST request to the server in order to create for the user a new account and then log him in!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.70.203