The Zend Framework blog has continued its series of posts focusing on the use of the Zend Expressive framework with a new tutorial covering handling OPTIONS and HEAD requests in an Expressive-based API.
In v1 releases of Expressive, if you did not define routes that included the OPTIONS or HEAD HTTP request methods, routing would result in 404 Not Found statuses, even if a specified route matched the given URI. RFC 7231, however, states that both of these request methods SHOULD work for a given resource URI, so long as it exists on the server. This left users in a bit of a bind.[...] In the case of a HEAD request, the specification indicates that the resulting response should be identical to that of a GET request to the same URI, only with no body content. This would mean having the same response headers. In the case of an OPTIONS request, typically you would respond with a 200 OK response status, and at least an Allow header indicating what HTTP request methods the resource allows. Sounds like these could be automated, doesn't it? In Expressive 2, we did!
The tutorial then shows you the code you'll need to add to your Expressive v2 application for handling each kind of request. It involves some custom middleware using the route
handling on the HEAD
request type for one and the other for OPTIONS
. The HEAD
requests return an empty response while the OPTIONS
requests return the data from a manually defined array (no automatic generation from routes or anything).