节点js(Express)express.static不起作用

时间:2017-10-30 11:05:19

标签: node.js express passport.js

我正在开发一个小应用,我只是使用Gmail帐户登录用户。问题是,当用户成功登录到应用程序时,会重定向到其他页面,从而产生错误404.

目录层次结构类似于enter image description here

Ejs文件在视图文件夹中

我在用户通过Google帐户登录时应将其重定向到欢迎页面但是它找不到错误页面。

默认页面代码在

下面
    "use strict"
    const path=require("path");
    const express=require("express");
    const session=require("express-session");
    const bodyParser=require("body-parser");
    const passport = require("passport");
    const db   =require("./DbConnection/findCollection");
    const auth = require("./auth");
    const compression = require("compression");
    var appDir = path.dirname(require.main.filename);

    const app=express();
    app.set("view engine", "ejs");

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

    //enable gzip
    app.use(compression()); 
    //enable session storage
    //TODO: add connect-mongo as session storage
    app.use(session({
        resave: false,
        saveUninitialized: false,
        secret:"keyboardcat",//config.get("SECRET"),
        signed: true
    }));
    app.all("*", (req, res, next) => {
        console.log("request: " + req.url);
        next();
    });
    //OAuth
    app.use(passport.initialize());
    app.use(passport.session());
    app.use(auth.router);

    function respond(req, res) {
        return function (err, data) {
            if (err) {
                return res.status(400).send(err);
            }

            res.header("Content-Type", "application/json");
            res.send(data);//JSON.stringify(data, null, 2));
        };
    }

    function render(req,res,file,data){
        res.render("master.ejs", { content: file, req: req, data: data});

    }

    app.get("/",(req,res,next)=>{
        if(req.user){
        console.log("Path is "+appDir);
    // res.redirect("/views/welcome");
        res.redirect("/welcome");
        }
        else{
            console.log("Path is "+appDir);
        render(req, res,"login.ejs");}
    });


    app.use("/views", express.static(__dirname + '/views'))

    app.all("*", (req, res) => {
        res.status(404).send("Page was not found, sorry!");
    });

    var server = app.listen(process.env.PORT || 3000, process.env.IP || "0.0.0.0", () => {
        var address = server.address();
        console.log(`[${(new Date().toString()).substr(0, (new Date().toString()).indexOf(" ("))}] Server started on http://${address.address}:${address.port}`);
    });

1 个答案:

答案 0 :(得分:0)

要使express能够加载视图文件,您应该输入

app.set('views', path.join(__dirname, 'views'));

而不是

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