javascript - 服务 worker js 中的 Fetch() 无法发送请求 header ?

标签 javascript google-cloud-messaging service-worker fetch-api

我的代码相同。我正在调用 fetch() 但网络和服务器中的请求没有像 cookie 这样的请求 header 。我又找到了一个帖子 Request headers not sent from Service Worker但它无法解决我的问题。

self.addEventListener('push', function (event) {
  event.waitUntil(
    self.registration.pushManager.getSubscription().then(function (subscription) {
      fetch('/user/get-notification', {
        mode: 'no-cors',
        method: 'post',
        headers: {
          'Authorization': 'Bearer ' + self.token,
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(subscription)
      }).then(function (response) {
        if (response.status != 'success') {
          console.log('Looks like there was a problem. Status Code: ' + response.status);
          throw new Error();
        }

        return response.json().then(function (data) {
          var title = data.title;
          var message = data.message;
          var icon = data.image;

          return self.registration.showNotification(title, {
            body: message,
            icon: icon
          });
        });
      }).catch(function (err) {
        console.error('Unable to retrieve data', err);
      });
    })
  );
});

最佳答案

要包含 cookie,您需要将 credentials 字段添加到您的请求中:

fetch('/user/get-notification', {
  credentials: 'include', // <-- To include cookies!
  mode: 'no-cors',
  method: 'post',
  headers: {
    'Authorization': 'Bearer ' + self.token,
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(subscription)
})

关于javascript - 服务 worker js 中的 Fetch() 无法发送请求 header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37437047/

相关文章:

javascript - JWT 是如何做 Authentication 的

javascript - 使用 WebGL 将三 Angular 形变成科赫雪花

javascript - 在 AngularFire2 身份验证中使用提供程序 UID 作为 Firestore ID

java - Android 与其他手机的连接

compiler-errors - 执行时出错-InstanceID instanceID = InstanceID.getInstance(getApplication());

android - 更新Google play服务到8.4.0推送通知后自己显示

firebase-cloud-messaging - Firebase 消息传递 "the site has been updated in background"

javascript - 如何在特定用户id下存储数据? Angular 火力基地

indexeddb - 无法从 Service Worker 访问 indexeddb

javascript - 如何在 fetch catch 中返回脱机文件的内容?