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

时间:2016-03-21 23:20:01

标签: node.js google-url-shortener

所以我在我的Angular应用程序上运行了谷歌的URL缩短程序,但因为它使用API​​密钥我认为在我使用Angular的服务器端进行谷歌api调用更聪明/更安全。

使用Angular发现Dnis $dnis非常直接的帖子但是我很快意识到我最好使用npm包begin raise 'Exception!' rescue => e puts "Rescued exception: #{e.message}" raise 'Something I did in this block raised an exception!' end ,但它似乎无法正常工作。

基本上我需要这样做:

$http

我现在写的是:

request

我一直收到错误:

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

我的要求错了吗?

感谢。

1 个答案:

答案 0 :(得分:1)

根据request documentation,您可以使用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()效果不错。