NodeJs Session,在Postman中工作但不在浏览器中工作

时间:2017-04-11 15:02:03

标签: node.js express-session

我在快速会话中遇到一些问题,我无法检索先前存储过的会话变量。以下是我编写的部分代码。

server.js

let express = require('express'),
    path = require('path'),
    bodyParser = require('body-parser'),
    cors = require('cors'),
    config = require('./config/database'),
    expressSession = require('express-session'),
    uid = require('uid-safe'),
    db;

let app = express();

//Import Routes
let auth = require('./routes/auth'),
    chimerListing = require('./routes/chimer-listing'),
    brandListing = require('./routes/brand-listing');

//Specifies the port number
let port = process.env.PORT || 3000;
// let port = 3000;

// Express session
app.use(expressSession({
    secret: "asdasd",
    resave: true,
    saveUninitialized: false,
    cookie: {
        maxAge: 36000000,
        secure: false
    }
}));

//CORS Middleware
app.use(cors());

//Set Static Folder
var distDir = __dirname + "/dist/";
app.use(express.static(distDir));

//Body Parser Middleware
app.use(bodyParser.json());

//MongoDB
let MongoClient = require('mongodb').MongoClient;

MongoClient.connect(config.database, (err, database) => {
    if (err) return console.log(err)
    db = database;

    //Start the server only the connection to database is successful
    app.listen(port, () => {
        console.log('Server started on port' + port);
    });    
});

//Make db accessbile to routers;
app.use(function(req, res, next) {
    req.db = db;
    res.set('Access-Control-Allow-Origin', '*');
    res.set('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.set('Access-Control-Allow-Headers', 'Content-Type');
    next();
});

//Routes
app.use('/login', auth);
app.use('/user-listing', userListing);
app.use('/brand-listing', brandListing);

//Index Route
app.get('/', (req, res) => {
    res.send('Invalid Endpoint');
});

genuuid = function() {
    return uid.sync(18);
};

auth.js

let express = require('express'),
    router = express.Router(),
    db;

//Login Router for chimer
router.post('/chimer', (req, res, next) => {
    db = req.db;

    // let client = req.client;
    db.collection('chimeUser').find({
        Username: req.body.username,
        Password: req.body.password
    }).toArray().then(function(docs) {
        //If there is such user
        if (docs.length >= 1) {
            req.session.chimerId = docs[0]._id;
            console.log(req.session);
            req.session.save(function(err) {
                    // session saved
                    if (err)
                        console.log(err)
                    res.json({
                        success: true,
                        chimerId: docs[0]._id
                            //objects: docs
                    });
                })
        } else {
            res.json({
                success: false,
                //objects: docs
            })
        }
    });
});

//Login Router brand
router.post('/brand', (req, res, next) => {
    db = req.db;
    db.collection('brand').find({
        Username: req.body.username,
        Password: req.body.password
    }).toArray().then(function(docs) {
        req.session.brand = docs;

        console.log(req.session.brand);
        //If there is such user
        if (docs.length >= 1) {
            res.json({
                success: true,
                //objects: docs
            })
        } else {
            res.json({
                success: false,
                //objects: docs
            })
        }
        //db.close()
    });
});
});

module.exports = router;

用户listing.js

let express = require('express'),
    moment = require('moment'),
    router = express.Router(),
    // ObjectID = require('mongodb').ObjectID,
    db, client;

// let applyListing = require('../models/chimer-listing');

//Retrieve All Listing
router.get('/getAllListing', (req, res, next) => {
    db = req.db;
    console.log(req.session)
    db.collection('listing').find().toArray().then(function(listing) {
        //If there is any listing
        if (listing.length >= 1) {
            res.json({
                success: true,
                results: listing
            })
        } else {
            res.json({
                success: false,
            })
        }
        //db.close()
    });
});
module.exports = router;

所以在我的server.js中,我有三个路由文件,即auth,用户列表和品牌列表。

首先,用户需要使用以angular2开发的Web应用程序登录,这将触发身份验证路由。然后它将检查凭据是否存在于数据库中(如果存在)我将为req.session.chimerId分配ID,以便在其他路由中我将能够使用此chimerId。

接下来,在用户登录后,他们将检索项目列表。出现问题的地方似乎无法检索我之前保存的req.session.chimerId。它将是未定义的

注意:我使用Postman和浏览器试过这个。在Postman中它可以工作,我能够找回req.session.chimerId而当我使用angular2应用程序来点击端点时req.session.chimerId总是为空

0 个答案:

没有答案