如何使用 ruby 中的 sinatra 获取请求正文 json?
How to get request body as json with sinatra in ruby?
我需要创建 api 服务器来接收 json。
此代码应接收查询并打印其中发送的 json 数据,但出现错误。服务器代码抛出 JSON::Parse 错误 765,我不知道为什么。
require 'sinatra'
require 'json'
post '/' do
push = JSON.parse(request.body.read)
puts "I got some JSON: #{push.inspect}"
end
这是我在 python 提出的要求。
requests.post("http://127.0.0.1:4567/",data = {1:'a'})
看起来你实际上并没有发送 JSON。
您使用的是 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
因此您发送的是表单编码数据,当您的服务器尝试将其解析为 JSON 时会导致错误。
要发送JSON,可以使用json
参数代替data
:
requests.post("http://127.0.0.1:4567/", json = {1:'a'})
请注意,您还需要更改服务器中的路由,以使其 returns 成为有效响应。
我需要创建 api 服务器来接收 json。 此代码应接收查询并打印其中发送的 json 数据,但出现错误。服务器代码抛出 JSON::Parse 错误 765,我不知道为什么。
require 'sinatra'
require 'json'
post '/' do
push = JSON.parse(request.body.read)
puts "I got some JSON: #{push.inspect}"
end
这是我在 python 提出的要求。
requests.post("http://127.0.0.1:4567/",data = {1:'a'})
看起来你实际上并没有发送 JSON。
您使用的是 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
因此您发送的是表单编码数据,当您的服务器尝试将其解析为 JSON 时会导致错误。
要发送JSON,可以使用json
参数代替data
:
requests.post("http://127.0.0.1:4567/", json = {1:'a'})
请注意,您还需要更改服务器中的路由,以使其 returns 成为有效响应。