I'm trying to add some middleware to a Rails project I'm working on, and when I try to do so, it seems to cause an endless loop.
Specifically, I have the following middleware shell file:
# app/middleware/log_data.rb
class LogData
def initialize(app)
@app = app
end
def call(env)
# To-do: Write code here.
end
end
I then created a new middleware
directory under the app
directory and put the file in that directory.
After that, I added the following towards the bottom of config/application.rb
:
config.middleware.use("LogData")
After restarting the Puma server running on Vagrant with sudo service puma restart
, if I run rake middleware
, I can see the middleware correctly show up in the list towards the bottom.
However, when I try to refresh the website, it fails with an endless loop, displaying the following in Chrome:
If I comment out the config.middleware.use("LogData")
line in config/application.rb
, then the middleware disappears from the rake middleware
command list, and the website stops crashing and loads properly.
What am I doing wrong? What am I missing? I imagine it's something simple, but I'm not sure why a simple (and empty) shell middleware file would cause the whole site to crash. Thank you.
I should note that I'm using Rails 4.2.11, which I know is old, but upgrading right now is not an option.
Your middleware does nothing, returns nil (which translates to an Incomplete Server Response), and basically the request ends there. It needs to return something (an array of [status, headers, response]
, or call the env) to allow the request to pass through the middleware chain.
# app/middleware/log_data.rb
class LogData
def initialize(app)
@app = app
end
def call(env)
# To-do: Write code here.
# this should be at the very end of the method
@app.call(env)
end
end
Here is more info about middlewares.