fetch request option

nextjs

The fetch function takes an optional second argument, an object containing the request options. Some common options include:

  • method: The HTTP method to use, such as ‘GET’, ‘POST’, ‘PUT’, etc.
  • headers: An object containing request headers.
  • body: The request body, for example when sending data in a POST request.
  • mode: The mode of the request, such as ‘cors’, ‘no-cors’, or ‘same-origin’.
  • credentials: The request credentials, such as ‘include’, ‘omit’, or ‘same-origin’.

Here’s an example of using these options:

const res = await fetch('/api/example', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    name: 'John',
    email: '[email protected]',
  }),
  mode: 'cors',
  credentials: 'include',
})

This example sends a POST request to the /api/example endpoint with a JSON body and sets the Content-Type header to application/json. The mode is set to cors and the credentials are set to include, allowing the browser to send cookies with the request.