Node.js 中 GCM 请求的 401

401 on GCM requests in Node.js

我正在尝试在我的应用程序后端设置 GCM 消息传递。

后台是运行Node.js

这是我正在使用的代码:

var apiKey = "AIz*******";
var postData = JSON.stringify({
    "notification": {
        "title": "Hello World"
    }
});

var options = {
    host: 'android.googleapis.com',
    port: 443,
    path: '/gcm/send',
    method: 'POST',
    headers: {
        'Authorization': 'key=' + apiKey,
        'Content-Type': 'application/json',
        'Content-Length': Buffer.byteLength(postData)
    }
};

var rqst = https.request(options, (response) => {
var responseBody = '';
    response.setEncoding('utf8');
    response.on('data', (chunk) => {
        responseBody += chunk;
    });
    response.on('end', () => {
        res.send(responseBody)
    });
});

rqst.on('error', (e) => {
    console.log('problem with request: ${e.message}');
});

rqst.write(postData);
rqst.end();

但我总是收到 401 答复:

<HTML>
    <HEAD>
        <TITLE>Unauthorized</TITLE>
    </HEAD>
    <BODY BGCOLOR="#FFFFFF" TEXT="#000000">
        <H1>Unauthorized</H1>
        <H2>Error 401</H2>
    </BODY>
</HTML>

我使用的 API 密钥取自 Google 开发人员控制台

API 管理器 > 凭据 > API 密钥

我是不是漏掉了什么?

你知道为什么我的请求未经授权吗?

由于您使用 NodeJS 作为 Web 服务器,因此请使用 IP 地址 API 密钥类型而不是 None。