代码之家  ›  专栏  ›  技术社区  ›  pedrommuller

Firebase云消息:请求包含无效参数

  •  0
  • pedrommuller  · 技术社区  · 6 年前

    我在跟踪这个 tutorial

    {
        error:
        {
            code: 400,
            message: 'Request contains an invalid argument.',
            status: 'INVALID_ARGUMENT'
        }
    }
    

    与使用curl发送请求不同,我使用的是node.js | express的云函数,代码如下:

    exports.messages = function (req, res) {
        const api = 'https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send';
        const headers = {
            'Accept': 'application/json',
            'Content-type': 'application/json',
        };
    
        return getAccessToken().then((accessToken) => {
            headers.Authorization = `Bearer ${accessToken}` // <-- accessToken is OK
            const { title, body, token } = req.body;
            return fetch(api, {
                headers,
                method: 'POST',
                body: JSON.stringify(
                    {
                        'message': {
                            'token': token, // <-- this is the client fcm token
                            'notification': {
                                'title': title,
                                'body': body
                            }
                        }
                    }
                )
            }).then(res => res.json()).then(data => {
                    console.log(data);
                    res.sendStatus(200);
                }).catch((error) => {
                    console.error(error);
                });
    
        });
    }
    

    其中,令牌是我的服务帐户的OAuth 2令牌

    function getAccessToken() {
        return new Promise(function (resolve, reject) {
            var key = require('../keys/service-account.json');
            var jwtClient = new google.auth.JWT(
                key.client_email,
                null,
                key.private_key,
                [
                    'https://www.googleapis.com/auth/firebase',
                    'https://www.googleapis.com/auth/firebase.database',
                    'https://www.googleapis.com/auth/firebase.messaging',
                ],
                null
            );
            jwtClient.authorize(function (err, tokens) {
                if (err) {
                    reject(err);
                    return;
                }
                resolve(tokens.access_token);
            });
        });
    }
    

    我错过了什么?任何建议都将不胜感激

    1 回复  |  直到 6 年前
        1
  •  1
  •   Regular User jack.the.ripper    6 年前

    我刚刚意识到我从教程中复制了fcm端点的uri。我改成了:

    const api = 'https://fcm.googleapis.com/v1/projects/{project-Id}/messages:send';