In Express under Node.js, I'd like to inspect a request under a specific path (say, /restricted
) and if it is acceptable, have the request be handled by the static provider, which handles the caching headers etc.
If I simply use app.get('/restricted/:file', ...)
and then use res.sendfile
to send the static file if approved, it will ignore any caching headers and always send the file.
I can't use a blanket logged-in check because different users should only get different files.
What is the best way to implement this?
redirect() function lets you redirect the user to a different URL by sending an HTTP response with status 302. The HTTP client (browser, Axios, etc.) will then "follow" the redirect and send an HTTP request to the new URL as shown below. const app = require('express')(); // The `res.
To serve static files such as images, CSS files, and JavaScript files, use the express.static built-in middleware function in Express. The root argument specifies the root directory from which to serve static assets. For more information on the options argument, see express.static.
Static files are files that clients download as they are from the server. Create a new directory, public. Express, by default does not allow you to serve static files. You need to enable it using the following built-in middleware. app.
var express = require("express");
var app = express.createServer();
var staticMiddleware = express.static(__dirname + "/public");
app.get("/restricted/:file", function(req, res, next) {
var authorized = true;
//Compute authorization appropriately here
if (authorized) {
staticMiddleware(req, res, next);
} else {
res.send(401);
}
});
app.listen(3456);
This will use the static middleware when appropriate including all of its functionality. Otherwise you can handle unauthorized requests as appropriate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With