使用XMLHttpRequest标头调用Nodejs Ajax

我正在为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}

我不知道我做错了什么。 谢谢你的帮助。

对于POST请求, curlContent-Typeapplication/x-www-form-urlencoded 。 Hubot使用Node的http客户端,OTOH不使用默认的Content-Type头。 如果没有明确的Content-Type头, http://strawpoll.me/api/v2/polls ://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)