Home > Software engineering >  How to do a POST request in a service-worker?
How to do a POST request in a service-worker?

Time:04-25

I'm trying to send a POST request to the back-end whenever a client click on a Push notification (front-end side), so I know the client have received the notification.

To send request from my front-end to my back-end I have the following system :

Alerte.js:

import Repository from "./repository";

const resource = "/notifications/updatestatus";
export default {
    post(payload) {
        return Repository.post(`${resource}`, payload);
    },
};

Repository.js:

import axios from "axios";
import store from "../store/index";
const baseURL = process.env.VUE_APP_API_BASE_URL;
axios.defaults.withCredentials = true;

const httpClient = axios.create({
  baseURL,
  headers: {
    "Content-Type": "application/json",
  },
  withCredentials: true,
});


httpClient.interceptors.response.use(undefined, (error) => {
  if (!error.status) {
// network error
    if(error.request.responseURL.split("/").pop() !== "login") {
      const payload = {
        type: "error",
        value:
          "Can't reach back-end",
      };
      store.commit("setAlert", payload);
    }
    console.error(error);
  }

  if (error.response.status === 401) {
    store.commit("resetUser");
  }
  return Promise.reject(error);
});

export default httpClient;

but I can't do that since I want to perform the call in the service-worker, which doesn't allow to import stuff (can't import outside of a module error)

service-worker.js

/* eslint-disable */
importScripts(
  "https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js"
);

importScripts('./env-vars.js')

workbox.core.skipWaiting();
workbox.core.clientsClaim();

self.__WB_MANIFEST;

// Stylesheet caching
workbox.routing.registerRoute(
  /\.(?:js|css)$/,
  new workbox.strategies.StaleWhileRevalidate({
    cacheName: "file-cache",
  })
);

// Image caching
workbox.routing.registerRoute(
  /\.(?:png|jpg|jpeg|svg|gif)$/,
  new workbox.strategies.CacheFirst({
    cacheName: "image-cache",
    plugins: [
      new workbox.expiration.Plugin({
        maxEntries: 50, // cache only 50 images
        maxAgeSeconds: 30 * 24 * 60 * 60, // 30 days
      }),
    ],
  })
);

self.addEventListener("push", (event) => {
  if (event.data) {
    console.log(`[Service Worker] Push had this data: "${event.data.text()}"`);
    const { title, ...options } = JSON.parse(event.data.text());
    self.registration.showNotification(title, options);
  }
});

self.addEventListener("notificationclick", (e) => {
  const { notification, action } = e;
  //notification.close();
  console.log(notification.data.id)
  console.log(notification.data.userId)
 /* let req = "{\"user\":{\"id\": "  e  "},\"id\": "  e  "}";
  Alerte.post(req).catch(error => {
    console.error(error)
  });*/

  if (action === "vote") {
    clients.openWindow(`${ENVERYWHERE_APP_BASE_URL}`);
  }
  else if (action === "invitation") {
    clients.openWindow(`${ENVERYWHERE_APP_BASE_URL}/groups`);
  }
});

workbox.precaching.precacheAndRoute([]);

So how can I manage to perform this request to my back-end ?

CodePudding user response:

Service Workers can use the browser's built-in fetch():

self.addEventListener("notificationclick", (e) => {
  
  let req = {
    id: /* REQUEST ID */,
    user: {
      id: /* USER ID */,
    },
  };

  fetch(/* URL */, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(req),
  }).catch(error => {
    console.error(error)
  });
});
  • Related