简体   繁体   English

服务工作者js中的Fetch()无法发送请求标头?

[英]Fetch() in service worker js not able to send request headers?

My code for the same.I am calling fetch() but the request in network and server has no request headers like cookie. 我的代码相同。我正在调用fetch()但网络和服务器中的请求没有像cookie这样的请求标头。 I found one more post for this Request headers not sent from Service Worker but it was not able to solve my problem. 我发现这个请求标题的帖子不是从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);
      });
    })
  );
});

To include cookies you need to add the credentials field to your request: 要包含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)
})

Headers is an interface, you can provide new set of options to it, by initializing. 标题是一个界面,您可以通过初始化为它提供新的选项集。 Something like this: 像这样的东西:

 headers: new Headers({
      'Authorization': 'Bearer ' + self.token,
      'Accept': 'application/json',
      'Content-Type': 'application/json'
 })

Well after browsing official documentation of service worker, I noticed addition of 在浏览了服务工作者的官方文档后,我注意到了

credentials: 'include' 凭证:'包含'

in fetch enable to send request headers.Thanks for the support though. 在fetch enable中发送请求头。但是感谢支持。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM