每當客戶端單擊推送通知(前端)時,我都會嘗試向后端發送 POST 請求,因此我知道客戶端已收到通知。
要將請求從我的前端發送到我的后端,我有以下系統:
警報.js:
import Repository from "./repository";
const resource = "/notifications/updatestatus";
export default {
post(payload) {
return Repository.post(`${resource}`, payload);
},
};
存盤庫.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;
但我不能這樣做,因為我想在服務人員中執行呼叫,這不允許匯入東西(不能在模塊錯誤之外匯入)
服務作業者.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([]);
那么我怎樣才能設法向我的后端執行這個請求呢?
uj5u.com熱心網友回復:
Service Worker 可以使用瀏覽器的內置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)
});
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/464819.html
標籤:javascript 节点.js Vue.js 邮政 工作箱
