Handling OPTIONS requests on my own
Hi! I wanted to ask about an exception that gets thrown if the OPTIONS request is handled anywhere in the stack. Here is sample code to reproduce copied from tets/app.options.js with an additional call to next() at the end:
var app = express();
app.options('/users', function(req, res, next){
res.set('Allow', 'GET');
res.send('GET');
next(); // added line
});
app.get('/users', function(req, res){});
app.put('/users', function(req, res){});
request(app)
.options('/users')
.expect('GET')
.expect('Allow', 'GET', done);
It looks like the default OPTIONS handler tries to send headers down after we already did so in our own handler. My use case for this is having logging middleware that gets hit at the very end after the response body is already sent, which requires me to call next() after res.end().
Ideally, if a handler for the OPTIONS request is already defined, it'd be nice to not call the default handler. I was going to writing a patch for this but ran into a few stumbling blocks I'd like to ask about. The possibilities so far:
Option 1: If OPTIONS middleware is defined, don't sendOptionsResponse()
This breaks app.all() which adds an OPTIONS handler by default; this test specifically: https://github.com/strongloop/express/blob/4.12.4/test/app.options.js#L33
I imagine that changing app.all not to add an OPTIONS handler would be a significant breaking change, so this didn't seem like the best idea.
Option 2: Checking that headers were already sent
If res.headersSent is set, we can reasonably assume that something else is already handling the OPTIONS call, since the default handler's job is to set Cross-Site related headers. But this option breaks another test: https://github.com/strongloop/express/blob/4.12.4/test/app.options.js#L75
Now, this test confuses me a bit. It assumes that the default handler will still run despite us having explicit OPTIONS middleware and that further middleware should be able to write the body. What's the use case for this? The original issue seems unrelated.
Thanks!
Once you call res.send(), you cannot call next(); there are no exception to this rule.
My use case for this is having logging middleware that gets hit at the very end after the response body is already sent, which requires me to call next() after res.end() .
It certainly doesn't. You can view the source code for Morgan as a logging example. I would be glad to help, but you provided no code for your real use case for me to comment and help with.
Most likely, all you need to do is use the on-finished module.
The most basic "logging middleware" example is the following:
var onFinished = require('on-finished');
app.use(function (req, res, next) {
// add listener for when the response finishes
onFinished(res, function () {
// log things; you have req and res in the scope
});
// continue on
next();
});
Once you can res.send(), you cannot call next(); there are no exceptions to this rule.
Why is that? I'm curious because I've always thought that middleware was just an abstraction for handling the request/response flow, regardless of the actual work performed in it but maybe I'm just terrible at reading docs. Appreciate the example code: I now know about the finish event in ServerResponse :speedboat:
I'm curious because I've always thought that middleware was just an abstraction for handling the request/response flow
It is; technically there is no reason why you cannot call next(); forbidding it is a simplification. If you don't follow this rule, though, you must ensure that every single route and middleware you used is checking to see if the response has been sent or not and take the appropriate action; this seems like a lot of work and even then, 99% of the time if you get into this situation, it's in error. Just consider a route where you accidentally called next() after responding, nothing blows up but it invokes some logic somewhere else in your codebase you never intended.
This is, for example, the problem you are getting with OPTIONS handling in Express: if it's reached, it's an error if you've already responded because it wants to respond. You will be able to, at some point, turn off the OPTIONS handling on a per-router basis (see #2246), so in this case, you would have to turn it off and then either ignore OPTIONS requests, or implement your own handler.
Another thing you can think of it is like a callback: calling res.send() is like calling the callback; then calling next() is now like calling the callback twice: you can certainly do it if you can manage to control everything top-to-bottom, but it's not recommend because it's against convention and other developers will not understand what is happening when they go to read the code.
@dougwilson What if I don't want to respond to options at all? Is there any option for that behavior?
PS: I couldn't see any option to disable that behavior.
@thesayyn You can always write code, e.g.
if (req.method.toUpperCase() === "OPTIONS") return next();
// Do whatever you would normally here.
@thesayyn You can always write code, e.g.
if (req.method.toUpperCase() === "OPTIONS") return next(); // Do whatever you would normally here.
This won't help the problem I've mentioned above.
I don't want to handle OPTIONS request at all. express's router handles options request if there's no one handled it already.
Let me clarify with an example;
const express = require('express');
const rootRouter = express.Router();
// These routers above have many routes inside them.
const myChildRouter = express.Router();
const mySecondChildRouter = express.Router();
// I don't care about what happening in those routers.
rootRouter.all('/myfeaturemodule1', myChildRouter);
rootRouter.all('/myfeaturemodule2', mySecondChildRouter);
// When I route to an indistinct route that does not start with feature module paths my callback will be called.
// However when I route to any indistinct route that starts with feature module paths
// my callback will never fire since child routers will be handling the unhandled options request
rootRouter.use((req,res) => {
if (! req.route ) {
// Route is unhandled
// My logic goes here
}
})
To work around this I need to put my handler everywhere in router tree. Does that make sense?
Please open a new issue, put what you out here, so it's obvious if you are having an issue you need to get resolved. You can always link to this issue if you think it is relevant, but posting in an issue closed years ago is greatly reducing the number of people who will see it and help.