节点js,使https发布请求谷歌api

时间:2016-08-06 18:34:18

标签: javascript node.js post https google-api

我正在尝试将google帐户登录集成到我正在构建的node.js应用程序中,并且我向google api gate发送https发布请求时遇到一些问题。

起初我正在关注此tutorial并且它运作良好,但他们在其中声明,对于Google帐户ID的后端处理,应该执行此操作tutorial。那时我开始遇到问题。我不想使用任何额外的库,只是本机node.js功能来了解它是如何完成的。

为了在后端验证帐户,需要将令牌ID安全地发布到给定的URL。

这是正在运行的客户端代码:

var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://www.googleapis.com/oauth2/v3/tokeninfo');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
    console.log(xhr.responseText);
};
xhr.send('id_token=' + token_id);

现在,当我尝试在服务器端使用nodejs时,它没有用。我尝试使用在nodejs docs上找到的代码:

var http = require('http');
var post_data = 'id_token=' + token_id;

var post_options = {
    host: 'googleapis.com',
    port: '80',
    path: '/oauth2/v3/tokeninfo',
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
    }
};

var post_req = http.request(post_options, function(res) {
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
        console.log(chunk);
    });
});

post_req.write(post_data);
post_req.end();

来自谷歌的回复是404错误The requested URL /oauth2/v3/tokeninfo was not found on this server. That's all we know.这意味着我做错了什么。所以我的问题是:

  1. 如何改进/修复我的代码,以便它执行正确的后https请求?
  2. 我怎么知道这是一个https请求(不是http)?
  3. 感谢您的帮助;)

1 个答案:

答案 0 :(得分:1)

除了协议的差异(http vs https)之外,您还缺少主机名中的www子域(就像客户端示例中使用的那样)。将其从host: 'googleapis.com'更改为host: 'www.googleapis.com'应该有效。

相关问题