How to perform redirects in NodeJS like a .htacces

2019-07-28 22:52发布

I have recently converted my full web application from PHP to NodeJS.

In Apache, I could use a .htaccess file to perform redirects. The main redirect I had within my application was redirecting all CSS and JS files from a unique name, to their correct path. This was to make sure that when I push an update to my server, all I need to do is change the global variable to have the client load all CSS and JS files from the server instead of from the cache.

For example, in my main PHP file I would include a global variable like so:

define('js_version', "7fn39tg");

Then in my PHP file I would include all JS and CSS files like so:

<script src="content/scripts/my-script__<?php echo js_version ?>.js"></script>

They would then get rendered client slide like this:

<script src="content/scripts/my-script__7fn39tg.js"></script>

Lastly, I would then use .htaccess to read the file from it's original location, being my-script.js:

RewriteRule ^(.+)\_\_(.+)\.(js)$ $1.$3 [L]

How could I do the above in NodeJS?

I'm thinking that I need to use EJS to render the version number inside the template, like so:

app.get('/', function (req, res) {
    res.render(__dirname + '/public/app.ejs', {
       "js_version": "7fn39tg"
    });
});

And include it in my app.ejs file like so:

<script src="content/scripts/my-script__<%= js_version %>.js"></script>

And then use app.use(function(req, res, next){.....} to somehow direct the file to it's actual path. I'm currently serving all static content from the following:

app.use(express.static(__dirname + '/public'));

1条回答
聊天终结者
2楼-- · 2019-07-28 23:50

You can redirect in Node using res.redirect('/redirect/path')

查看更多
登录 后发表回答