Nextjs + Express +护照;请求用户未定义

时间:2018-11-09 11:48:09

标签: javascript node.js express next.js

我第一次尝试使用Nextjs,我添加了express以使用mongodb。到目前为止,我已经使用自己的Google凭据登录了,但是我正在努力将会话信息发送到用户的个人资料页面。

Server.js:

const express = require('express');
const next = require('next');
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
mongoose.Promise = global.Promise;
const passport = require("passport");
const LocalStrategy = require("passport-local");
const exsession = require("express-session");
const User = require('../models/User');
const port = process.env.PORT || 8080;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();

const middleware = require("../middleware/middleware")

const uri = "XXXX"

 app.prepare()
        .then(() => {
            const server = express();
            const showRoutes = require('./routes/index');
            const authRouter = require('./routes/auth');

    mongoose.connect(uri)
    .then(function () {
        console.log('Connected to MONGOD !!');
    }).catch(function (err) {
        console.log('Failed to establish connection with MONGOD !!');
        console.log(err.message);
    });

    server.use(express.static(__dirname + "/public"));
    server.use(bodyParser.urlencoded({extended: true}));
    server.use(bodyParser.json());

    /////////////////////////////////////
    //passport configuration
    /////////////////////////////////////
    server.use(exsession({
        secret: "projectx",
        resave: false,
        saveUninitialized: false,
    }));
    server.use(passport.initialize());
    server.use(passport.session());

    passport.use(new LocalStrategy(User.authenticate()));
    passport.serializeUser(User.serializeUser());
    passport.deserializeUser(User.deserializeUser());

    server.use(function(req, res, next){
        res.locals.currentUser = req.user;
        next();
    })

    server.use('/api', showRoutes);

    server.use('/auth', authRouter);

    server.get('/login', (req, res) => {
        return app.render(req, res, '/login', req.query )
    })

    server.get('/profile', middleware.isLoggedIn, (req, res, next) => {
        console.log(req.query)
        return app.render(req, res, '/profile', { user: req.user } )
    })

    server.get('/post/:id', (req, res) => {
        return app.render(req, res, '/post', { id: req.params.id })
    })

    server.get("*", (req, res) => {
        return handle(req,res);
    })

    server.listen(port, err => {
        if (err) throw err;
        console.log(`> Ready on http://localhost:${port}`)

    })
})
.catch(ex => {
    console.log(ex.stack);
    process.exit(1);
})

Profile.js:

import React, { Component } from 'react'

export default class extends Component {
  static getInitialProps ({ user: { user } }) {
    console.log(user)
    return { user: user }
  }

  render () {
    return <div>
      <h1>Welcome{this.props.user}</h1>
    </div>
  }
}

我试图在个人资料页面中显示当前用户的姓名,但在控制台中却未定义。

0 个答案:

没有答案