简体   繁体   中英

Routing example.com to a static file but example.com/anything to something else in Express-JS

I am new to Parse and I am trying to deploy my app to, say, example.com .

I want example.com to serve a static landing page, but example.com/anything (of course, anything is NOT a literal, it can be anything) to be handled by another controller.

To make it more clear:

Scenario 1: User types www.example.com in their web browser.

Output: My static landing page, say, index.html

Scenario 2: User types www.example.com/ausername in their web browser.

Output: Result of rendering an ejs page server-side.

How can I achieve this in a very simple manner? I've tried:

app.get('/:username', function(req, res){
    res.render("user", { username: req.params.username });
});

This does work for example.com/ausername but when I type example.com , the request is again rendered by the above method, creating an error.

You can put your static index.html in a 'public' folder in your project root and use the express.static() middleware to deliver that static page.

// Serve the static landing page at the root
// e.g. public/index.html => http://www.example.com/
app.use(express.static(__dirname + '/public'));

// Serve the route
// e.g. http://www.example.com/test123
app.get('/:username', function(req, res){
    res.render("user", { username: req.params.username });
});

This will allow users to visit your static page at the root, and also visit your route when a value is supplied. See the Express middleware documentation for more information.

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