简体   繁体   中英

How to serve dynamic static files in express JS

I am trying to render static file. I came across the sendFile() method but it is not working with proxy. I need help. Here is my code.

var express = require('express');
const proxy = require('express-http-proxy');
var process = require('process');

var app = express();
app.set('port', (process.env.PORT || 8080));

app.use('$Variable',  express.static(__dirname + '$Variable'));
app.use('/', proxy(function(request, response) {
  return 'http://localhost:8000' + request.url
}))

process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
app.listen(app.get('port'));
setTimeout(function() {
  process.exit();
}, 100000);

I want something like this does anyone has idea? What can I do to replace the $variable with path to my files. NOTE: $VARIABLE is just there to showcase what I am trying to mean. It does not means that I am trying to use PHP in node.js. Think before you become a professor.

To take the path from the URL and append "/webapp" onto the end of it and then look for a file in your file system that matches that to serve, you could do this:

const path = require('path');

app.get((req, res, next) => {
    const file = path.join(__dirname, req.path, "webapp");
    res.sendFile(file, { dotfiles: "deny" }, (err) => {
        if (err) {
            console.log(err);
            // decide what you want to do here with an error
            // either call next(err), call next() to continue routing
            // or send a 404 response
            res.sendStatus(404);
        }
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM