如何从Firebase托管执行Google Cloud Functions?

时间:2019-06-12 11:03:50

标签: firebase-cloud-messaging google-cloud-functions firebase-hosting

我正在尝试创建一个Android项目,该项目可以将通知从一个Android设备发送到另一个。为此,我创建了一个node.js文件,该文件在本地服务器上运行良好。但是,当我将其托管在Google Cloud Platform上时,它会显示“找不到页面”。它无法通过托管调用Google Function。它正在寻找或执行index.html,但应该执行index.js,该文件位于在使用Firebase初始化项目时创建的功能目录中。

我从这段视频中引用了以下内容:https://youtu.be/pnysHgQvOiM?list=PLk7v1Z2rk4hjM2NPKqtWQ_ndCuoqUj5Hh

index.js文件

  const functions = require('firebase-functions');

   var {google}  = require('googleapis')

 var MESSAGING_SCOPE ="https://www.googleapis.com/auth/firebase.messaging"

  var SCOPES = [MESSAGING_SCOPE]

  var express = require('express')
  var app = express();
  var bodyParser = require('body-parser');
  var router = express.Router();
  var request = require('request');
  app.use(bodyParser.urlencoded({extended:true}));
  app.use(bodyParser.json());
  router.post('/send',function(req,res){

    getAccessToken().then(function(access_token){

    var title = req.body.title;
    var body = req.body.body;
    var token = req.body.token;

    request.post({ 
        headers:{
            Authorization: 'Bearer '+ access_token 
        }, url: 
  "https://fcm.googleapis.com/v1/projects/my_project_name/messages:send",
        body: JSON.stringify(


            {
                "message":{
                  "token" : token,
                  "notification" : {
                    "body" : body,
                    "title" : title
                    }
                 }
              }
        )

    },function(error,reponse,body){

        res.end(body);
        console.log(body);
           });
     });

   });

      app.use('/api',router);



       function getAccessToken()
{
     return new Promise(function(resolve,reject){

var key= require("./service-account.json");
var jwtClient = new google.auth.JWT(


    key.client_email,
    null,
    key.private_key,
    SCOPES,
    null
);

jwtClient.authorize(function(error,tokens){

    if(error)
    {
        reject(error)
    }
    resolve(tokens.access_token)
  // console.log(tokens.access_token)
});

   jwtClient.authorize(function(error,tokens){

    if(error)
    {
        reject(error)
    }
    resolve(tokens.access_token)
    console.log(tokens.access_token)
  });

  });

 }
    exports.api = functions.https.onRequest(app);

firebase.json

    { 
        "hosting": 
           {

"public": "public",


"rewrites": [
    {
      "source": "/api/send",
      "functions": "api"
    }
  ],
   "ignore": [
    "firebase.json",
    "**/.*",
    "**/node_modules/**"
 ]

               }

            }

此代码在使用http://localhost:8085/api/send时可以正常工作,但不能在https://my_project_name.firebaseapp.com/api/send中使用

0 个答案:

没有答案