2017-10-24 20 views
0

私はポート4000上で動作するフロントエンドのプッシュ通知に加入&を処理するための次のコードを持っている:プッシュ通知のポップアップが表示されないのはなぜですか?

var endpoint; 
    var key; 
    var authSecret; 

    // We need to convert the VAPID key to a base64 string when we subscribe 
    function urlBase64ToUint8Array(base64String) { 
    const padding = '='.repeat((4 - base64String.length % 4) % 4); 
    const base64 = (base64String + padding) 
     .replace(/\-/g, '+') 
     .replace(/_/g, '/'); 

    const rawData = window.atob(base64); 
    const outputArray = new Uint8Array(rawData.length); 

    for (let i = 0; i < rawData.length; ++i) { 
     outputArray[i] = rawData.charCodeAt(i); 
    } 
    return outputArray; 
    } 

    function determineAppServerKey() { 
    var vapidPublicKey = 'BAyb_WgaR0L0pODaR7wWkxJi__tWbM1MPBymyRDFEGjtDCWeRYS9EF7yGoCHLdHJi6hikYdg4MuYaK0XoD0qnoY'; 
    return urlBase64ToUint8Array(vapidPublicKey); 
    } 

export default function registerServiceWorker() { 
    if('serviceWorker' in navigator) { 
     navigator.serviceWorker.register(`${process.env.PUBLIC_URL}\sw.js`).then(function(register){ 
      console.log("worked", register) 
     return register.pushManager.getSubscription() 
      .then(function(subscription) { 

       if (subscription) { 
       // We already have a subscription, let's not add them again 
       return; 
       } 

       return register.pushManager.subscribe({ 
        userVisibleOnly: true, 
        applicationServerKey: determineAppServerKey() 
       }) 
       .then(function(subscription) { 

        var rawKey = subscription.getKey ? subscription.getKey('p256dh') : ''; 
        key = rawKey ? btoa(String.fromCharCode.apply(null, new Uint8Array(rawKey))) : ''; 
        var rawAuthSecret = subscription.getKey ? subscription.getKey('auth') : ''; 
        authSecret = rawAuthSecret ? 
        btoa(String.fromCharCode.apply(null, new Uint8Array(rawAuthSecret))) : ''; 

        endpoint = subscription.endpoint; 
        alert("came here") 
        return fetch('http://localhost:3111/register', { 
        method: 'post', 
        headers: new Headers({ 
         'content-type': 'application/json' 
        }), 
        body: JSON.stringify({ 
         endpoint: subscription.endpoint, 
         key: key, 
         authSecret: authSecret, 
        }), 
        }) 

       }); 
      }); 
     }).catch(function(err){ 
      console.log("Error",err) 
     }) 
    } 
} 

を、サーバーのコードは次のようになります。

const webpush = require('web-push'); 
const express = require('express'); 
var bodyParser = require('body-parser'); 
var path = require('path'); 
const app = express(); 

// Express setup 
app.use(express.static('public')); 
app.use(bodyParser.json()); 
app.use(bodyParser.urlencoded({  // to support URL-encoded bodies 
    extended: true 
})); 

function saveRegistrationDetails(endpoint, key, authSecret) { 
    // Save the users details in a DB 
} 

webpush.setVapidDetails(
    'mailto:[email protected]', 
    'BAyb_WgaR0L0pODaR7wWkxJi__tWbM1MPBymyRDFEGjtDCWeRYS9EF7yGoCHLdHJi6hikYdg4MuYaK0XoD0qnoY', 
    'p6YVD7t8HkABoez1CvVJ5bl7BnEdKUu5bSyVjyxMBh0' 
); 

// Home page 
app.get('/', function (req, res) { 
    res.sendFile(path.join(__dirname + '/index.html')); 
}); 

// Article page 
app.get('/article', function (req, res) { 
    res.sendFile(path.join(__dirname + '/article.html')); 
}); 

// Register the user 
app.post('/register', function (req, res) { 

    var endpoint = req.body.endpoint; 
    var authSecret = req.body.authSecret; 
    var key = req.body.key; 

    // Store the users registration details 
    saveRegistrationDetails(endpoint, key, authSecret); 

    const pushSubscription = { 
    endpoint: req.body.endpoint, 
    keys: { 
     auth: authSecret, 
     p256dh: key 
    } 
    }; 

    var body = 'Thank you for registering'; 
    var iconUrl = 'https://raw.githubusercontent.com/deanhume/progressive-web-apps-book/master/chapter-6/push-notifications/public/images/homescreen.png'; 

    webpush.sendNotification(pushSubscription, 
    JSON.stringify({ 
     msg: body, 
     url: 'https://localhost:3111', 
     icon: iconUrl, 
     type: 'register' 
    })) 
    .then(result => { 
     console.log("came here ") 
     console.log(result); 
     res.sendStatus(201); 
    }) 
    .catch(err => { 
     console.log(err); 
    }); 

}); 

// The server 
app.listen(3111, function() { 
    console.log('Example app listening on port 3111!') 
}); 

サーバーが稼動31114000ポートに移動すると、Allow/Blockポップアップが表示され、Allowを指定すると、サーバーで行われたとおりにサーバーからThank you for registeringというメッセージが送信されます。しかし、Thank you for registeringのポップアップは表示されず、コンソールにエラーはありません。

注:私は3111に、chrome-extensionを使用してCORSを有効にしています。

+0

「CORSを有効にする」 - CORSをどこで有効にしていますか?あなたが投稿したコードのどこにいても、Corsや関連するアクセス制御が許可されているというヘッダは表示されません。 –

+0

@ JaromandaX:chrome-extensionを使用して、質問 – batman

+0

を更新しました。 'バイパスされたCORS –

答えて

-1

私は自宅でpythonサーバーを持っているので、あなたのサーバーに依存する可能性があり、通知apiを使用すると、私はhttpsサイトにいない限り通知しません。それは問題ではない場合、私はコードエラーがあると仮定しますが、私はブロードキャストチャンネルとxhrなどを使用することができると信じています:let b = new BroadcastChannel;b.onmessage(function(){XmlHTTPRequest('POST', {Data: "yes"})};)と通知をプッシュするxhrを使用してください。

関連する問題