I am trying to write a script for Hubot to make an AJAX call to Strawpoll.me. I have a cURL command that works exactly how I want but I am having trouble translating that into a Node.js function.
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
Here is what I currently have in my script.
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)
The script version is returning {"error":"Invalid request","code":40}
I can't tell what I am doing wrong. Thanks for your help.
For POST requests, curl
sets the Content-Type
to application/x-www-form-urlencoded
. Hubot uses Node's http client, which OTOH, doesn't use any defaults for the Content-Type
header. Without an explicit Content-Type
header, the resource at http://strawpoll.me/api/v2/polls
is not able to discern the request body. You'll have to set the Content-Type
header manually to mimic curl's request.
robot.http('http://strawpoll.me/api/v2/polls')
.headers({'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/x-www-form-urlencoded'})
.post(data)