1

所以我让谷歌的 URL 缩短器在我的 Angular 应用程序上工作,但是因为它使用 API 密钥,我认为在我使用 Angular 的服务器端进行谷歌 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"   
}]

我的要求错了吗?

谢谢。

4

1 回答 1

1

根据请求文档json,您可以使用该选项发布 JSON 数据。

json - 将 body 设置为值的 JSON 表示并添加 Content-type: application/json 标头。此外,将响应正文解析为 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()效果很好。

于 2016-03-21T23:47:20.617 回答