简体   繁体   中英

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

I'm using Sinatra. I've got a button that sends a JSON-formatted string to the server by making a POST request. Only problem is, the JSON string isn't getting to the server.

Here's index.erb :

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

Here's 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 :

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. But when I check the Ruby console, it prints {} for params . If it worked right, I guess params would show a JSON object in string form, along with whatever else it would show.

I'm running Sinatra on my machine, at address 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?

"params" is most likely looking for URL encoded query string values. You want the Body content of the post, not the params.

See How to parse JSON request body in Sinatra just once and expose it to all routes?

您需要解析JSON正文:

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

Alex Hill is right. And the the post he mentioned show one way to solve it.

An other way is to use 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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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