简体   繁体   English

为什么这个POST请求不会向服务器发送JSON字符串?

[英]Why won't this POST request send a JSON string to the server?

I'm using Sinatra. 我正在使用Sinatra。 I've got a button that sends a JSON-formatted string to the server by making a POST request. 我有一个按钮,通过发出POST请求将JSON格式的字符串发送到服务器。 Only problem is, the JSON string isn't getting to the server. 唯一的问题是,JSON字符串没有到达服务器。

Here's index.erb : 这是index.erb

<input id="post-button" type="button" value="Send POST request">

Here's script.js : 这是script.js

window.onload = function(){
  var btn = document.getElementById('post-button');
  btn.onclick = function(){
    var req = new XMLHttpRequest();
    var reqObj = {
      name: 'Joe',
      age: '100'
    };
    var reqJSON = JSON.stringify(reqObj);

    req.open('POST','/post_target',true);
    req.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
    req.send(reqJSON);
  }
}

And finally, main.rb : 最后, main.rb

get '/' do 
    erb :index
end

post '/post_target' do 
    p params
end

When I click the button and check Firebug, I see that the browser sent a POST request. 当我单击按钮并检查Firebug时,我看到浏览器发送了一个POST请求。 But when I check the Ruby console, it prints {} for params . 但是当我检查Ruby控制台时,它会为params打印{} If it worked right, I guess params would show a JSON object in string form, along with whatever else it would show. 如果它工作正常,我猜params将以字符串形式显示JSON对象,以及它将显示的任何其他内容。

I'm running Sinatra on my machine, at address http://localhost:4567 . 我正在我的机器上运行Sinatra,地址为http://localhost:4567

What am I doing wrong? 我究竟做错了什么? If I need to do the request with jQuery, I can do that, but can it be done with "vanilla" JavaScript? 如果我需要使用jQuery执行请求,我可以这样做,但可以使用“vanilla”JavaScript吗?

"params" is most likely looking for URL encoded query string values. “params”最有可能寻找URL编码的查询字符串值。 You want the Body content of the post, not the params. 你想要帖子的Body内容,而不是params。

See How to parse JSON request body in Sinatra just once and expose it to all routes? 请参阅如何在Sinatra中解析JSON请求主体一次并将其暴露给所有路由?

您需要解析JSON正文:

parsed_params = JSON.parse( request.body.read, symbolize_names:true )

Alex Hill is right. Alex Hill是对的。 And the the post he mentioned show one way to solve it. 而他提到的帖子显示了一种解决方法。

An other way is to use rack/contrib: 另一种方法是使用rack / contrib:

require it: 需要它:

require 'rack'
require 'rack/contrib'

add the middleware 添加中间件

use Rack::PostBodyContentTypeParser

source: http://jaywiggins.com/2010/03/using-rack-middleware-to-parse-json/ 来源: http//jaywiggins.com/2010/03/using-rack-middleware-to-parse-json/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM