Passport js在本地工作,但不能在远程服务器上工作

时间:2018-07-10 11:51:31

标签: node.js angular http express passport.js

在本地主机上成功运行应用程序后,尝试在远程服务器上运行它。但随后所有问题再次出现。 我使用护照js进行了登录http请求。

我的客户是: 登录-

this.http.post(Consts.REMOTE_URL + '/login', {
      username: username,
      password: password
    }, {withCredentials:true})

获取请求-

    const headers = new Headers({ 'Content-Type': 'application/json'});
    const options = new RequestOptions({params: formattedParams, headers: headers,withCredentials:true});
    this.http.get(completeUrl, options)
      .subscribe(onSuccess, onError);

我的服务器端看起来像这样:

server.js:

const express = require('express')
const passport = require('passport')
const winston = require('winston')
const db = require('./db')
require('dotenv').config()

const port = process.env.PORT || 9000
const app = express()

require('./config/passport')(passport, db)
require('./config/express')(app, passport, db.pool, db)
require('./app/routes')(app, passport)

app.use(function (err, req, res, next) {
  if (err.message && (~err.message.indexOf('not found'))) {
    return next()
  }
  winston.error(err.stack)
  return res.status(500).json({error: 'Error on backend occurred.'})
})

const server = app.listen(port, () => {
  console.log("listening to port: "+port);
  if(app.get('env') === 'test') return

  winston.log('Express app started on port ' + port)
})

server.on('close', () => {
  winston.log('Closed express server')

  db.pool.end(() => {
    winston.log('Shut down connection pool')
  })
})

express.js:

const path = require('path')
const express = require('express')
const expressHandlebars = require('express-handlebars')
const expressValidator = require('express-validator')
const session = require('express-session')
const pgSession = require('connect-pg-simple')(session)
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
const methodOverride = require('method-override')
const morgan = require('morgan')
const winston = require('winston')
const config = require('./')
const resumable = require('../app/lib/resumablejs')
const env = process.env.NODE_ENV || 'development'

module.exports = (app, passport, pool, db) => {
    let log = 'dev'
    if (env !== 'development') {
    log = {
      stream: {
        write: message => winston.info(message)
      }
    }
  }

    if (env !== 'test') app.use(morgan(log))

    app.engine('handlebars', expressHandlebars())
    app.set('view engine', 'handlebars')

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

    app.use(methodOverride(function (req) {
        if (req.body && typeof req.body === 'object' && '_method' in req.body) {
            var method = req.body._method
            delete req.body._method
            return method
        }
    }))

    app.use(cookieParser())
    app.use(session({
        store: new pgSession({
            pool
        }),
        secret: config.session_secret,
         saveUninitialized: false,
         resave: false,
         cookie: { maxAge: 14 * 24 * 60 * 60 * 1000 }
    }))

    /////////////////////////////////////////
    app.use(function(req,res,next){
        res.header("Access-Control-Allow-Origin",req.headers.origin);
        res.header('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Accept');
        res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
        res.header('Access-Control-Allow-Credentials', true);
        next();
    })
    //////////////////////////////////////////

    app.use(passport.initialize())
    app.use(passport.session())

    app.use('/', express.static(path.join(config.root, 'public')))
    app.use('/files', resumable(undefined, undefined, db))
}

passport.js:

passport.serializeUser((user, done) => {
    done(null, user)//stored the user inside req.user 
  })

  passport.deserializeUser((user, cb) => {
    var id = user.id; 
    const queryString = squel.select().from('users').field('id').field('username').field('type').where('id = ?', parseInt(id, 10)).toString();
    db.query(queryString, (err, results) => {
      if(err) {
        winston.error('Error when selecting user on session deserialize', err)
        return cb(err)
      }

      cb(null, results.rows[0])//restored the user inside req.user
    })
  })

在localhost上一切正常,但是当我在远程服务器上设置dist文件夹时,已执行登录,但未定义'req.user'。

请求之间的区别在于,在本地主机上,我有一个cookie,而会话是保存用户,而在服务器上则没有。

0 个答案:

没有答案