如何在 service-worker 中执行 POST 请求?

How to do a POST request in a service-worker?

我试图在客户端单击推送通知(前端)时向后端发送 POST 请求,因此我知道客户端已收到通知。

为了将请求从我的前端发送到我的后端,我有以下系统:

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;

但我不能那样做,因为我想在 service-worker 中执行调用,它不允许导入东西(无法在模块错误之外导入)

服务-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([]);

那么我如何设法向我的后端执行此请求?

Service Workers 可以使用浏览器的 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)
  });
});