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

时间:2018-08-13 21:06:53

标签: node.js firebase firebase-cloud-messaging google-cloud-functions

我正在关注此tutorial,现在我正要向fcm端点发送HTTP请求,但是出现以下错误:

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

我不是使用curl发送请求,而是使用node.js的云函数|用以下代码表示:

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 个答案:

答案 0 :(得分:1)

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

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

成功了!