如何 return 来自前块的 JSON 响应
How to return a JSON response from a before block
我正在编写基于 Sinatra 的 API,并希望使用 API 密钥保护某些端点,在处理路由之前验证密钥。
我理解为什么在 before
块中抛出错误不起作用,因为尚未调用 begin
/rescue
语句,但是我想要一个 JSON 将错误消息作为 JSON 对象发送回客户端的响应。
我该怎么做?
namespace '/v1/sponser/:key' do
before do
if APIHelper.valid_key?(params[:key]) == false
throw 'Error, invalid API key'
# is it possible to return a JSON response from the before statement here?
end
end
get '/test' do
begin
json status: 200, body: 'just a test'
rescue => error
json status: 404, error: error
end
end
end
我会考虑使用 halt
:
before do
unless APIHelper.valid_key?(params[:key])
halt 404, { 'Content-Type' => 'application/json' },
{ error: 'Error, invalid API key' }.to_json
end
end
get '/test' do
json status: 200, body: 'just a test'
end
您可以使用 halt
方法 return 响应特定代码,body 和 headers。所以它看起来像这样:
before do
halt 401, {'Content-Type' => 'application/json'}, '{"Message": "..."}'
end
它看起来很草率,所以你可以重定向到另一个 url,它提供一些服务
我正在编写基于 Sinatra 的 API,并希望使用 API 密钥保护某些端点,在处理路由之前验证密钥。
我理解为什么在 before
块中抛出错误不起作用,因为尚未调用 begin
/rescue
语句,但是我想要一个 JSON 将错误消息作为 JSON 对象发送回客户端的响应。
我该怎么做?
namespace '/v1/sponser/:key' do
before do
if APIHelper.valid_key?(params[:key]) == false
throw 'Error, invalid API key'
# is it possible to return a JSON response from the before statement here?
end
end
get '/test' do
begin
json status: 200, body: 'just a test'
rescue => error
json status: 404, error: error
end
end
end
我会考虑使用 halt
:
before do
unless APIHelper.valid_key?(params[:key])
halt 404, { 'Content-Type' => 'application/json' },
{ error: 'Error, invalid API key' }.to_json
end
end
get '/test' do
json status: 200, body: 'just a test'
end
您可以使用 halt
方法 return 响应特定代码,body 和 headers。所以它看起来像这样:
before do
halt 401, {'Content-Type' => 'application/json'}, '{"Message": "..."}'
end
它看起来很草率,所以你可以重定向到另一个 url,它提供一些服务