Google 云消息传递:通过 JavaScript 请求发送 UTF-8 数据

Google Cloud Messaging: Send UTF-8 data via JavaScript request

我想用 GCM 发送带有元音符号 (äüöß) 的文本,但在发送请求时总是出现以下异常:

{"to":"/topics/mytopic","data":{"message":"ö;ä;1471125600000;1471211999999"}}

undefined:1
JSON_PARSING_ERROR: Unexpected token END OF FILE at position 106.
^
SyntaxError: Unexpected token J
  at Object.parse (native)
  at IncomingMessage.<anonymous> (c:\project\path\gcm.js:43:30)
  at IncomingMessage.emit (events.js:129:20)
  at _stream_readable.js:908:16
  at process._tickCallback (node.js:355:11)

当我发送没有变音符号的文本时,一切正常,我得到了结果。

这里是我的 JavaScript 函数:

exports.sendMessage = function (req, res) {

var topic = req.body.topic;
var message = req.body.message;

var data = JSON.stringify({
    "to": "/topics/" + topic,
    "data": {
        "message": message
    }
});

var options = {
    host: 'gcm-http.googleapis.com',
    path: '/gcm/send',
    method: 'POST',
    headers: {
        'Authorization': 'key=xxx',
        'Content-Type': 'application/json; charset=utf-8',
        'Content-Length': data.length
    }
};

var req2 = http.request(options, function(resp) {
    var msg = '';
    resp.setEncoding('utf-8');
    resp.on('data', function(chunk) {
        msg += chunk;
    });
    resp.on('end', function() {
        console.log(JSON.parse(msg));

        if(JSON.parse(msg).message_id) {
            res.send(200, {msg: "Message sent successfully! Message: " + JSON.parse(msg).message_id});
        } else {
            res.send(400, {msg: "Message sending failed! Message: " + JSON.stringify(msg)});
        }
    });
});

req2.write(data);
req2.end();

};

我做错了什么?我需要在发送前重新编码 message 字符串吗?

经过几个小时的搜索,我终于找到了它 - 删除 Content-Length 对我有用。所以我的请求 options 现在看起来如下:

var options = {
    host: 'gcm-http.googleapis.com',
    path: '/gcm/send',
    method: 'POST',
    headers: {
        'Authorization': 'key=xxx',
        'Content-Type': 'application/json; charset=utf-8'
        // NO CONTENT-LENGTH PARAMETER ANYMORE!!!
    }
};