Patrick Mevia Patrick Mevia - 1 year ago 76
Javascript Question

node js, make https post request to google api

I am trying to integrate google account login into the node.js application i am building and i have a little problem sending a https post request to google api gate.

At first i was following this tutorial and it worked alright, but they stated in it that for backend processing of google account id, one should do this tutorial. I started to having problems at that point. I didnt want to use any extra libraries, just native node.js functionality to get my head around how its done.

In order to validate account on backend, one needs to securely post o token id to a given url.

This is the client side code that is working:

var xhr = new XMLHttpRequest();'POST', '');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
xhr.send('id_token=' + token_id);

Now when i tried to do it with nodejs on server side it didnt work. I tried with the code i found on nodejs docs:

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

var post_options = {
host: '',
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.on('data', function (chunk) {


The response from google was 404 error
The requested URL /oauth2/v3/tokeninfo was not found on this server. That's all we know.
Which means that i did something wrong. So my questions are:

  1. how can i improve/fix my code so it executes proper post https request?

  2. how do i know that it will be a https request (not http)?

Thank You for any help ;)

Answer Source

Aside from the difference in protocol (http vs https), you're also missing the www subdomain in the hostname (like what is being used in your client-side example). Changing it from host: '' to host: '' should work.