Nodejs Ajax使用XMLHttpRequest标头调用

时间:2015-03-02 16:28:33

标签: ajax node.js hubot

我正在尝试为Hubot编写一个脚本,以便对Strawpoll.me进行AJAX调用。我有一个cURL命令,它可以正常工作,但我无法将其转换为Node.js函数。

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 个答案:

答案 0 :(得分: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)
相关问题