具有JSON有效负载的Crossrider ajax帖子请求在Rails后端中无法正确接收

Crossrider ajax post requests having JSON payload are not received correctly in Rails backend

本文关键字:后端 Rails 请求 负载 有效 JSON Crossrider ajax 具有      更新时间:2023-09-26

我有一个JSON对象,我想把它发布到远程服务器(Rails)。所有将其作为"application/json"发送到服务器的尝试都会失败,其中 POST 参数在某处转换为 url 编码的字符串。例如:

appAPI.request.post({
  url: "http://mybackend",
  postData: {hello: 'world', foo: 'bar'},
  onSuccess: function(response) {
    console.log("postback succeeded with response: " + response)
  },
  onFailure: function(httpCode) {
    console.log("postback failure: " + httpCode)
  },
  contentType: 'application/json'
});

返回 HTTP 500,服务器从格式错误的 JSON 对象发出报告:

Error occurred while parsing request parameters.
Contents:
MultiJson::LoadError (784: unexpected token at 'hello=world&foo=bar'): 
  /Users/hammady/.rvm/rubies/ruby-1.9.3-p448/lib/ruby/1.9.1/json/common.rb:148:in `parse'
  ...

我应该怎么做才能将JSON对象发送到我的Rails后端?

您需要先将对象字符串化。

postData: JSON.stringify({hello: 'world', foo: 'bar'});

使用 JSON.stringify 来字符串化发布的数据

appAPI.request.post({
  url: "http://mybackend",
  postData: JSON.stringify({hello: 'world', foo: 'bar'}),
  onSuccess: function(response) {
    console.log("postback succeeded with response: " + response)
  },
  onFailure: function(httpCode) {
    console.log("postback failure: " + httpCode)
  },
  contentType: 'application/json'
});