简体   繁体   中英

How to use route for html file already served as static

I use passport.js to authenticate user after he enters login page. To keep user logged in when he returns to home page i'm going to use something like:

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

app.get('/', function(req,res){
   if(req.user){
   // connect to database ....
} else{
    res.sendFile(__dirname +'/index.html');
   }
});

Note that index.html file is inside "public" folder. Recently i realized that having a code like above, node.js doesn't use app.get('/'....) route but it serves index.html directly. So i'm unable to check if req.user exists. Any suggestion?

As You might understand express.static handles index.html before Your router.

But You cannot avoid express.static also (otherwise You have to use nginx or write own static file output).

So You've to re-think Your folder structure or have to develop 2 separate apps: api (backend) and frontend (that will request to api for data)

In context of Your question I wrote an example app where I organize assets, html files and app routes:

1) Have such folder structure:

文件夹结构

2) and example app.js :

'use strict';

const express = require('express');
const app = express();
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');

app.set('trust proxy', 1);

// attaching renderer
app.engine('.html', require('ejs').renderFile); // ejs renderer will render .html files as ejs files
app.set('view engine', 'html');          // views has .html extension
app.set('views', __dirname + '/public'); // views live in public folder

// attaching common middlewares
app.use('/assets', express.static('public/assets')); // our static assets will live in public/assets folder
app.use(cookieParser());
app.use(bodyParser());


// implement and attach passport auth somewhere (:
// remove it after passport has been attached:
const authorizeUser = (req, res, next) => {
  req.user = {id: 1, username: 'test'};
  next();
};

app.get('/', authorizeUser, (req, res) => {
  res.render('index', {user: req.user});  // render get index.html from views folder (see above)
});

app.listen(8080, () => {
  console.log('App listening');
});



ps download example app from here (don't forget to call npm i inside extracted folder (; )

ps implement passport.js Yourself

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