Search code examples
node.jsgoogle-url-shortener

Node - request - And Google URL shortener


So i got Google's URL shortener working on my Angular app however as it uses an API Key i thought it smarter/safer to do the google api call on my server side where I'm using Angular.

Found $http posts very straight forward with Angular however with Node i quickly realised I better use the npm package request however it doesn't seem to work.

So essentially I need to do:

POST https://www.googleapis.com/urlshortener/v1/url
Content-Type: application/json
{"longUrl": "http://www.google.com/"}

And I've currently written:

//Load the request module
var request = require('request');

//Configure and make the request
request({
        url: 'https://www.googleapis.com/urlshortener/v1/url?key=XXXXXXXXX',
        method: 'POST',
        headers: { //We can define headers too
        'Content-Type': 'application/json'
        },
        data: {
        'longUrl': 'http://www.myverylongurl.com'
        }
    }, function(error, response, body){
        if(error) {
            console.log(error);
        } else {
            console.log(response.statusCode, response.body);
        }
});

I keep getting the error:

"errors": [{ "domain": "global", "reason": "required", "message": "Required",    "locationType": "parameter”, “location": "resource.longUrl"   
}]

Is my request wrong?

Thanks.


Solution

  • According to the request documentation, you can post JSON data with the json option.

    json - sets body to JSON representation of value and adds Content-type: application/json header. Additionally, parses the response body as JSON.

    In your case it would be:

    request.post('https://www.googleapis.com/urlshortener/v1/url?key=xxxx', {
      json: {
        'longUrl': 'http://www.hugocaillard.com'
      }
    }, function (error, response, body) {
      if(error) {
        console.log(error)
      } else {
        console.log(response.statusCode, body)
      }
    })
    

    Note: you could also use the request() method (all I did was changing data: with json:), but here request.post() works well enough.