完成数据库提取后触发passport.js回调

时间:2017-11-30 21:05:23

标签: node.js express passport.js mysqljs

我需要将Passport.js Facebook登录信息重定向到一个配置文件路由,该路由器呈现EJS视图,为其提供用户对象以及一些其他数据(消息数组)从数据库异步获取。

不幸的是,我收到此错误

  

无法GET / auth / facebook / callback

这是我的server.js代码

// Import ExpressJS
let express = require("express");
let app = express();

// Import Body Parser
let bodyParser = require("body-parser");

// Import Express Session Middleware
let session = require("express-session");

// Import EJS template engine
let ejs = require("ejs");

// Import custom middlewares
let flash = require("./middlewares/flash");
let setUser = require("./middlewares/flash");

// Import Message model
let Message = require ("./models/message");

// Import the user model
let User = require("./models/user");

// Import PassportInitializer
let passport = require("./config/passport.js");

// Import keys
let keys = require("./config/keys");

app

// Templating
.set('view engine',"ejs")

//Middlewares

// parse application/x-www-form-urlencoded
.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
.use(bodyParser.json())

//Use middlewares
.use(passport.initialize())
.use(passport.session())

// Set-up and Use Express Session
.use(session({
  secret: keys.session.secret,
  resave: false,
  saveUninitialized: true,
  cookie: { secure: false }
}))

.use(flash)

//Routes
.use("/assets",express.static("public"))


// Home
.get("/",(req,res)=>{

    Message.all((messages)=>{
        res.render("pages/index",{messages:messages});
    })
})

//Single message
.get("/message/:id",(req,res)=>{
    Message.find(req.params.id,(message)=>{
        if(message===null){
            res.status(400).send('<h1>HTTP Error 400: Bad Request!</h1>');
        } else {
            res.render("messages/show",{message:message});
        }

    });

})

// Facebook OAuth
.get("/auth/facebook/",passport.authenticate("facebook"))

// Facebook OAuth callback
.get('/auth/facebook/callback',passport.authenticate("facebook"),(req,res)=>{
        Message.all((messages)=>{res.send(messages)});

})

// Handle posted/sent message
.post("/",(req,res)=>{
    //If the message body is empty
    if(req.body.message===undefined || req.body.message===""){
        //flash an error message
        req.flash("error","Empty message :(");
        // Redirect to home
        res.redirect("/")
    // If the message body is not empty
    } else {
        // Create a new message and save it.
        Message.create(req.body.message,()=>{
            req.flash("success","Message added :)");
            // Redirect to home
            res.redirect("/");
        }); 
    }
})

// Listen on port
.listen(process.env.PORT || 3000, function(){
  console.log("Express server listening on port %d in %s mode", this.address().port, app.settings.env);
});

我的message.js文件

// Import Message model
let connection = require ("../config/db");

// Import Moment Session Middleware
let moment = require("moment");


// Import Message model
let connection = require ("../config/db");

// Import Moment Session Middleware
let moment = require("moment");


class Message{
    constructor(row){
        this.row = row;
    }
    get id(){
        return this.row.id;
    }
    get content(){
        return this.row.content;
    }
    get created_at(){
        return moment(this.row.created_at);
    }

    static all(callback){

        // Get all messages from DB
        connection.query("SELECT * FROM message",(error,results,fields)=>{
            if(error) throw error;

            // Run the callback function once terminated
            callback(results.map((result)=>{
                return new Message(result);
            }));
        });

    }

}

// Export the Message class
module.exports = Message;
// Export the Message class
module.exports = Message;

1 个答案:

答案 0 :(得分:0)

虽然我不知道这是一个肮脏的解决方法还是一个可接受的解决方案,但我可以把它弄清楚。

我必须添加一个异步获取用户&amp;的中间件。 消息数据然后呈现EJS视图。

这是代码

//..
// Facebook OAuth
.get("/auth/facebook/",passport.authenticate("facebook"))

// Facebook OAuth callback
.get('/auth/facebook/callback',passport.authenticate("facebook"),(req,res)=>{

})

.use((req,res,next)=>{
    Message.all((messages)=>{
        let userId = req.session.passport.user;
        if(userId){
            User.find(userId,(user)=>{
            res.render("pages/index",{user:user,messages:messages});
        });
        } else {
            next();
        }
    });
})
//..