Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/39.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js NodeJs会话,在邮递员中工作,但不在浏览器中工作_Node.js_Express Session - Fatal编程技术网

Node.js NodeJs会话,在邮递员中工作,但不在浏览器中工作

Node.js NodeJs会话,在邮递员中工作,但不在浏览器中工作,node.js,express-session,Node.js,Express Session,我在express会话中遇到一些问题,无法检索以前存储的会话变量。下面是我写的部分代码 server.js let express = require('express'), path = require('path'), bodyParser = require('body-parser'), cors = require('cors'), config = require('./config/database'), expressSession = r

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

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;
user-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、user list和brand list

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

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


注意:我用邮递员和浏览器试过了。在《邮递员》中,它起作用了,我能够检索回
req.session.chimerId
而当我使用angular2应用程序点击端点时
req.session.chimerId
总是空的

您的angular 2代码是从不同的原点运行的吗?我将其与nodejs应用程序一起构建,并且我还将nodejs配置为允许所有原点