在Node JS中渲染静态文件之前如何渲染路由?

时间:2018-10-15 09:05:51

标签: node.js authentication static public

我要先渲染app.use('/', callback function),然后再渲染来自公用文件夹的静态文件。

基本上,我在访问网站之前就进行了身份验证,因此一旦获得身份验证,就应该从公用文件夹加载index.html(静态文件)。

我应该怎么做?

我正在使用IBM的W3ID对网站进行身份验证。

const express = require('express');

const session = require('express-session');

const passport = require('passport');

const WebAppStrategy = require("ibmcloud-appid").WebAppStrategy;

const CALLBACK_URL = "public/index.html";

var path = require('path');

var bodyParser = require('body-parser');

var port = process.env.VCAP_APP_PORT || 8080;

var mongoose = require('mongoose');


//var MongoStore = require('connect-mongo')(session);

const app = express();

// mongodb connection

mongoose.connect("mongodb://admin:admin123@ds261430.mlab.com:61430/events");

var db = mongoose.connection;

// mongo error

db.on('error', console.error.bind(console, 'connection error:'));

// parse incoming requests

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use(express.static(path.join(__dirname, 'public')));
app.set('views', path.join(__dirname, 'views'));


// Set view engine as EJS
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

// include routes



app.use(session({
     secret: "123456",
     resave: true,
     saveUninitialized: true
     }));
 app.use(passport.initialize());
 app.use(passport.session());

passport.use(new WebAppStrategy({
 tenantId: "73585f35-8d9c-4f6f-9ab2-d07ca0c1d371",
 clientId: "863fce57-a717-4586-b8a2-0bf221ef4e68",
 secret: "MzkxMTMxMWMtNmYxNi00ZjNhLWFiNzctZjFlM2NkMDM1ZTkz",
 oauthServerUrl: "https://appid-oauth.eu-gb.bluemix.net/oauth/v3/73585f35-8d9c-4f6f-9ab2-d07ca0c1d371",
 redirectUri: "https://csi.eu-gb.mybluemix.net/" + CALLBACK_URL
 }));

passport.serializeUser(function(user, cb) {
 cb(null, user);
 });

passport.deserializeUser(function(obj, cb) {
 cb(null, obj);
 });

app.get(CALLBACK_URL, passport.authenticate(WebAppStrategy.STRATEGY_NAME));

app.use('/',passport.authenticate(WebAppStrategy.STRATEGY_NAME), function(req, res) {`enter code here`
    // do your authentication
});

// listen on port 8080
app.listen(port);

1 个答案:

答案 0 :(得分:0)

您可以将app.use('/',...)放在app.use('/',express.static('...'))上方。

您可以通过将选项{index:false}传递给express.static来实现,例如

app.use('/',express.static('path here',{index:false}));

此选项会将express.static设置为默认情况下不发送index.html