2015-03-02 112 views
1

我正在嘗試爲Hubot編寫一個腳本來對Strawpoll.me進行AJAX調用。我有一個cURL命令,它完全按照我的想法工作,但我無法將其轉換爲Node.js函數。Nodejs使用XMLHttpRequest調用Ajax頭文件

curl --header "X-Requested-With: XMLHttpRequest" --request POST --data "options=1&options=2&options=3&options=4&options=5&title=Test&multi=false&permissive=false" http://strawpoll.me/api/v2/polls 

這是我目前在腳本中的內容。

QS = require 'querystring' 

module.exports = (robot) -> 
    robot.respond /strawpoll "(.*)"/i, (msg) -> 
     options = msg.match[1].split('" "') 
     data = QS.stringify({ 
      title: "Strawpoll " + Math.floor(Math.random() * 10000), 
      options: options, 
      multi: false, 
      permissive: true 
      }) 
     req = robot.http("http://strawpoll.me/api/v2/polls").headers({"X-Requested-With": "XMLHttpRequest"}).post(data) (err, res, body) -> 
      if err 
      msg.send "Encountered an error :(#{err}" 
      return 
      msg.reply(body) 

腳本版本返回{"error":"Invalid request","code":40}

我不能告訴我在做什麼錯。謝謝你的幫助。

回答

1

對於POST請求,curlContent-Type設置爲application/x-www-form-urlencoded。 Hubot使用Node的http客戶端,該OTOH不使用Content-Type標頭的任何默認值。如果沒有明確的Content-Type標頭,則http://strawpoll.me/api/v2/polls處的資源無法辨別請求正文。您必須手動設置Content-Type標題以模仿curl的請求。

robot.http('http://strawpoll.me/api/v2/polls') 
    .headers({'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/x-www-form-urlencoded'}) 
    .post(data) 
+0

就是這樣!非常感謝。 – ericsaupe 2015-03-02 19:28:33