node.js - Firebase 云消息传递 : Request contains an invalid argument

标签 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);
            });

    });
}

其中 token 是我的服务帐户的 OAuth 2 token

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);
        });
    });
}

我在这里缺少什么?任何建议将不胜感激

最佳答案

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

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

成功了!

关于node.js - Firebase 云消息传递 : Request contains an invalid argument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51830565/

相关文章:

javascript - node.js 中的异步 https 请求

javascript - Web Streams 和 Node.js Stream API 之间的区别

ios - 如何在 Swift 中为图像使用 URL?

android - FirebaseRemoteConfig.activateFetched() 已弃用。改用什么?

firebase - 需要澄清 FCM 优先级与交货时间

javascript - 类型错误 : Cannot read property 'indexOf' of undefined in Nodejs

javascript - Node.js 我如何组合相似的对象

java - 如何检查 Java 中的 firebase 任务是否完成?

ios - Swift Firebase Cloud Messaging - 在后台发送上游消息

java - 自定义通知,如 Inshorts