BkdD
BkdD

Reputation: 593

401 on GCM requests in Node.js

I'm trying to setup GCM messaging on my application backend.

The backend is running with Node.js

This is the code I'm using:

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

But I always receive a 401 answer:

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

The API key I use is take from the Google developers console on

API Manager > Credentials > API key Google developers console API Manager > Credentials > API key

API Manager > Dashboard

Am I missing something?

Do you know why are my requests unauthorized?

Upvotes: 0

Views: 824

Answers (1)

ReyAnthonyRenacia
ReyAnthonyRenacia

Reputation: 17651

Since you are using NodeJS as web server, use the IP Addresses API key type instead of None.

Upvotes: 1

Related Questions