ajax - 使用 XMLHttpRequest header 进行 Nodejs Ajax 调用

标签 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}

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

最佳答案

对于 POST 请求,curlContent-Type 设置为 application/x-www-form-urlencoded。 Hubot 使用 Node 的 http 客户端,OTOH,它不使用 Content-Type header 的任何默认值。如果没有显式的 Content-Type header ,http://strawpoll.me/api/v2/polls 上的资源将无法识别请求正文。您必须手动设置 Content-Type header 以模仿curl 的请求。

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

关于ajax - 使用 XMLHttpRequest header 进行 Nodejs Ajax 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28814714/

相关文章:

javascript - 没有 MicrosoftAjax.js 和 MicrosoftMvcAjax.js 的 ASP.NET MVC

c# - 显示月份日历模型并与用户交互的更好方法

javascript - ajax jquery同步回调成功

node.js - 如何将关键字 Nullable(或 allowNull)添加到 Ajv 中?

php - AJAX 调用中止后服务器无响应

node.js - 在 sequelize 中搜索 (column1 + column2 +column3) <= column4

node.js - 模型相互引用错误 : circular dependencies problem

javascript - Hubot - 未输入参数/未输入参数

node.js - 在hubot brain中生成表格并插入值

javascript - 如何使用 Hubot 运行异步 Ruby 脚本?