0

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.

5
  • It's not clear to me what you're trying to do. Perhaps show several examples of incoming URLs and what files in your file system you want served for each URL. And, describe how $variable is determined. What value does it have? Commented Aug 19, 2022 at 15:13
  • When I call /test1 i want to render /test1/webapp and When I call /test2/webapp i want to rn.der /test2/webapp. I want these links to replace $variable. there are thousands of folders like these and I can't create so many app.get call. Commented Aug 19, 2022 at 15:16
  • Is that the only value for the URL you want to serve this way or do you want to take any prefix from any URL and do that with it? What is there's more than one part to the path like /test1/foo? You really haven't specified enough info in your question for people to know how to help. Please edit the question to include all relevant detail. Commented Aug 19, 2022 at 15:17
  • see the edited comment Commented Aug 19, 2022 at 15:19
  • I posted an answer and you suddenly went silent. Is that what you wanted? Commented Aug 19, 2022 at 16:11

1 Answer 1

1

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);
        }
    });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.