Reputation: 681
I went to MDN and read about the fetch
API and it says:
You can also optionally pass in an init options object as the second argument
Suppose, we have this simple login function:
const login = () => {
const requestOptions = {
method: "POST",
headers: { "Content-type": "application/json" },
body: JSON.stringify({ username, password })
}
return fetch(`apiUrl/users/authenticate`, requestOptions)
.then(res = res.json)
.then(data => console.log(data))
}
So, requestOptions
is an init
object here?
Upvotes: 4
Views: 3901
Reputation: 10604
Init
object is the options with which you can initialize the fetch methods.
The below are the most commonly used options that you can pass to fetch
as in init
object.
1. method: 'POST', // *GET, POST, PUT, DELETE, etc.
2. mode: 'cors', // no-cors, *cors, same-origin
3. cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
4. credentials: 'same-origin', // include, *same-origin, omit
5. headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
7. redirect: 'follow', // manual, *follow, error
8. referrerPolicy: 'no-referrer', // no-referrer, *client
9. body: JSON.stringify(data) // body data type must match "Content-Type" header
You can read more bout this on MDN
Upvotes: 2
Reputation: 371049
Yes, that's the "init
" object. It's not a very descriptive name, unfortunately, but that's what the official specification calls it. You can see the properties it accepts at MDN or in the specification:
dictionary RequestInit {
ByteString method;
HeadersInit headers;
BodyInit? body;
USVString referrer;
ReferrerPolicy referrerPolicy;
RequestMode mode;
RequestCredentials credentials;
RequestCache cache;
RequestRedirect redirect;
DOMString integrity;
boolean keepalive;
AbortSignal? signal;
any window; // can only be set to null
};
(the notation is a bit odd if you're not familiar with it - the part on the left is the type of the value, and the part on the right is the name of the property)
Upvotes: 1