节点 - 请求 - 和 Google URL shorterer

Node - request - And Google URL shortener

所以我在我的 Angular 应用程序上使用了 Google 的 URL 缩短器,但是因为它使用 API 键,我认为它 smarter/safer在我使用 Angular.

的服务器端执行 google api 调用

发现 $http 使用 Angular 的帖子非常直接,但是使用 Node 我很快意识到我最好使用 npm 包 request 但是它似乎不起作用。

所以基本上我需要做的是:

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

我目前写的是:

//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);
        }
});

我一直收到错误消息:

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

我的请求有误吗?

谢谢。

根据request documentation,您可以post JSON 数据与json 选项。

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

你的情况是:

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)
  }
})

注意:您也可以使用 request() 方法(我所做的只是将 data: 更改为 json:),但这里 request.post() 效果很好。