Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preflight request failing on calling a POST request with keepalive using fetch api

I am getting an error Preflight request for request with keepalive specified is currently not supported on calling a POST request using the fetch api with keepalive enabled. Any help would be appreciated . I am calling this api on beforeunload event.

API Request

  fetch(uri, {
    method: 'POST',
    headers: {
      'Content-type': options.headers.get('content-type'),
      'Authorization': options.headers.get('authorization')
    },
    body: JSON.stringify(interactionBody),
    keepalive: true
  }).catch((e) => {
    console.log(e);
  });
like image 640
Vinz and Tonz Avatar asked Apr 18 '19 00:04

Vinz and Tonz


People also ask

What is fetch api request keepalive?

keepalive. The keepalive option can be used to allow the request to outlive the page. Fetch with the keepalive flag is a replacement for the Navigator.sendBeacon() API. signal. An AbortSignal object instance; allows you to communicate with a fetch request and abort it if desired via an AbortController .

What does the fetch() method do?

The fetch() method in JavaScript is used to request data from a server. The request can be of any type of API that return the data in JSON or XML. The fetch() method requires one parameter, the URL to request, and returns a promise.

How to use fetch in js?

The simplest use of fetch() takes one argument — the path to the resource you want to fetch — and does not directly return the JSON response body but instead returns a promise that resolves with a Response object.

Is fetch API secure?

The serverless function returns the data back into your client application. Since the serverless function runs securely on the hosting providers servers and is responsible for the requests, the API key is never handled directly by the client, and is therefore secure.


1 Answers

I found a workaround until the Chrome issue fixed

it working when using mode: 'same-origin'

fetch(uri, {
  method: 'POST',
  headers: {
    'Content-type': options.headers.get('content-type'),
    'Authorization': options.headers.get('authorization')
  },
  body: JSON.stringify(interactionBody),
  mode: 'same-origin',
  keepalive: true
})
like image 114
Elhay Avichzer Avatar answered Oct 13 '22 17:10

Elhay Avichzer