Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirecting to a static file in express.js

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?

like image 237
w00t Avatar asked Feb 26 '12 21:02

w00t


People also ask

How use redirect in Express JS?

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.

Can Express serve static files?

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.

What is static file in Express JS?

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.


1 Answers

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.

like image 101
Peter Lyons Avatar answered Sep 21 '22 01:09

Peter Lyons