Sinatra Doesnt Handle HEAD Requests
I was building a simple API around GET, POST, and HEAD requests and it turns out Sinatra doesn’t handle HEAD requests for the server root ("/"). Don’t believe me? Try this.
get '/' do
puts 'This is a GET'
'GET is OK'
end
post '/' do
puts 'This is a POST'
'POST is OK'
end
head '/' do
puts 'This is a HEAD (root)'
response['X-Message'] = 'HEAD is OK'
end
head '/nonroot' do
puts 'This is a HEAD (non-root)'
response['X-Message'] = 'HEAD is OK'
end
Now, open up Postman and send a request to each of the three. When you get to the HEAD, you’ll get a 404 and although the application displays the HEAD request, it doesn’t call the puts
so “This is a HEAD” doesn’t get written to the console. Now, send a HEAD request to “/nonroot” and we see the puts string as well as the header.
The “Routes” code at https://sinatrarb.com/intro.html with the server root URI is also missing a head
block - it lists get, post, put, patch, delete, options, link and unlink.
Both the before and after filters work for HEAD requests to the server root URI.