简体   繁体   中英

How to get request body as json with sinatra in ruby?

I need to create api server which will receive json. This code should receive query and print json data sent in it, but something get wrong. Server code throws JSON::Parse error-765 and I don't know why.

require 'sinatra'
require 'json'

post '/' do
  push = JSON.parse(request.body.read)
  puts "I got some JSON: #{push.inspect}"
end

Here is my requests I make in python.

requests.post("http://127.0.0.1:4567/",data = {1:'a'})

It looks like you're not actually sending JSON.

Are you using the Python Requests library ? If so, the docs say :

Typically, you want to send some form-encoded data — much like an HTML form. To do this, simply pass a dictionary to the data argument. Your dictionary of data will automatically be form-encoded when the request is made

So you are sending form encoded data, which causes an error when your server tries to parse it as JSON.

To send JSON, you can use the json parameter instead of data :

requests.post("http://127.0.0.1:4567/", json = {1:'a'})

Note that you will also need to change the route in the server so that it returns a valid response.

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