节点 – 请求 – 和谷歌URL缩短

所以我得到谷歌的URL缩短工作在我的Angular应用程序,但是,因为它使用API​​密钥我认为这是更智能/更安全的做我的服务器端的谷歌API调用,我正在使用Angular。

发现$httppost非常直接与Angular,但是,我很快意识到,我最好使用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" }] 

我的要求错了吗?

谢谢。

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

json – 将body设置为值的JSON表示,并添加Content-type:application / json头。 另外,将响应主体parsing为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()工作得不错。