Fetch() allows us to get data from the API asynchronously without installing any additional libraries.
The above piece of code is a simple
fetch() get request. In the
fetch() method, there’s one mandatory argument, which is
url is a path from which the user would like to get data. Then
fetch() method returns a promise that can resolve the response object or reject it with an error.
The second arguments in the
fetch() method are options, and they’re optional. If the user won’t pass the options, the request always gets, and it downloads the content from the given URL. As I mentioned before, the promise returns the response object, and because of that, users need to use another method to get a body of the response. There are a few different methods that users can use depending on the format of the body.
The most popular one is
The above piece of code is a get method and a simple callback for a response and an error. When users are creating a config object, they can define a bunch of properties. The most common are
As a response, Axios returns a promise that’ll resolve with the response object or an error object. In the response object, there are the following values:
data: Actual response body
status: HTTP status code of the call, like
statusText: HTTP status as a text message
headers: The same as in the request
config: Request configuration
request: XMLHttpRequest (XHR) object
Users need to work with two promises in
fetch(). Users can avoid boilerplate and write cleaner, more succinct code in Axios.
Axios uses the
data property, but
fetch() uses the
body property to deal with data.
data is stringified. In
fetch(), the URL is passed as an argument, but in Axios the URL is set in the config object.