我正在使用Sinatra + Ruby + MongoDB创建一个简单的API,通过GET工作没有问题,但是通过POST是的...我尝试接收参数但是这是空的,我不知道我是不是我做的事情不好。我不使用view html,只是请求和响应JSON。我通过POST使用POSTMAN传递参数,但没有。
代码:app.rb
require 'rubygems'
require 'sinatra'
require 'mongo'
require 'json/ext'
require './config/Database'
require_relative 'routes/Estudiantes'
require_relative 'routes/OtherRoute
Code Estudiantes.rb
# Rest Collection Student
collection = settings.mongo_db['estudiantes']
# Finding
get '/estudiantes/?' do
content_type :json
collection.find.to_a.to_json
end
# find a document by its ID
get '/estudiante/:id/?' do
content_type :json
collection.find_one(:_id => params[:id].to_i).to_json
end
# Inserting
post '/new_estudiante/?' do
content_type :json
student = params # HERE
puts 'Parameters: ' + student
new_id = collection.insert student
document_by_id(new_id)
end
# Updating
post '/update_name/:id/?' do
content_type :json
id = BSON::ObjectId.from_string(params[:id].to_s)
puts 'ID: ' + params[:id].to_s
name = params[:name].to_s # HERE
age = params[:age].to_i # HERE
puts 'Name and Age: ' + name + age.to_s
collection.update({:_id => id}, {'$set' => {:name => name, :age => age} })
document_by_id(id)
end
post '/post/?' do
puts params[:name].to_json # HERE
end
由于
答案 0 :(得分:2)
<强>解决方案:强>
您应该应用JSON.parse,然后读取参数
代码
post '/post/?' do
params = JSON.parse request.body.read
puts params['name']
end