无法使用快速js

时间:2017-12-20 19:47:04

标签: node.js express session cors

我无法访问已保存在MongoStore会话中的内容。简而言之,算法是:client(http://localhost:8080)向服务器发送POST请求(http://localhost:3000/);程序成功创建会话,注册/登录用户,然后重定向到客户端(http://localhost:8080/finish-registration),然后该页面又发出另一个尝试检索会话的POST请求(http://localhost:3000/s),但它不可用

router.post('/s', function(req, res) {
        console.log('ID in POST: ', req.session.userId);
});

返回未定义

以下是我的服务器设置。对于后端,我使用expressjs,express-session,mongostore,frontend:与axios发生反应以发送请求。有谁知道我在做错了什么?感谢

server.js

const express = require('express');
const app = express();
const cors = require('cors');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const session = require('express-session');
const MongoStore = require('connect-mongo')(session);
const routes = require('./routes/router');

// connect to MongoDB
mongoose.connect('mongodb://localhost/testForAuth');
const db = mongoose.connection;

// handle mongo error
db.on('error', console.error.bind(console, 'connection error'));
db.once('open', () => {
    console.log('we are connected');
});

// use sessions for tracking logins
app.use(
    session({
        secret: 'work_hard',
        resave: true,
        saveUninitialized: true,
        store: new MongoStore({
            mongooseConnection: db
        })
    })
);

app.use(function(req, res, next) {
    // Website you wish to allow to connect
    res.header('Access-Control-Allow-Origin', 'http://localhost:8080');
    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    // Request headers you wish to allow
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);
    next();
});

// parse incoming requests
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// serve static files from template
app.use(express.static(__dirname + ''));

// include routes

app.use('/', routes);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    const err = new Error('File not found');
    err.status = 400;
    next(err);
});

// error handler
// define as the last app.use callback
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.send(err.message);
});

// listen on port 3000
app.listen(3000, () => {
    console.log('Express app listening on port 3000');
});

路由/ router.js

const express = require('express');
const router = express();
const cors = require('cors');
const fs = require('fs');
const User = require('../models/user.js');



// POST route for updating data
router.post('/', function(req, res, next) {
    if (req.body.email && req.body.password && req.body.confirmPassword) {
        if (req.body.password !== req.body.confirmPassword) {
            var err = new Error('Passwords do not match');
            err.status = 400;
            res.send('Passwords do not match');
            return next(err);
        } else {
            console.log(req.body.email, req.body.password);
            var userData = {
                email: req.body.email,
                password: req.body.password,
                confirmPassword: req.body.confirmPassword,
                registrationFinished: false
            };

            User.create(userData, function(error, user) {
                if (error) {
                    console.log("COULDN't create user");
                    return next(error);
                } else {
                    console.log('ADDED NEW USER');
                    req.session.userId = user._id;
                    return res.redirect('/profile');
                }
            });
        }
    } else if (req.body.email && req.body.password) {
        User.authenticate(req.body.email, req.body.password, function(error, user) {
            if (error || !user) {
                var err = new Error('Wrong email or password');
                err.status = 401;
                return next(err);
            } else {
                console.log('LOGIN!!!');
                req.session.userId = user._id;
                return res.redirect('/profile');
            }
        });
    } else {
        var err = new Error('All fields required');
        err.status = 400;
        return next(err);
    }
});

router.post('/s', function(req, res) {
    console.log('ID in POST: ', req.session.userId);
});

router.get('/s', function(req, res) {
    console.log(req.session.userId);
    return res.redirect('http://localhost:8080/finish-registration');
});


// GET route after registering
router.get('/profile', function(req, res, next) {
    console.log(`Find by id: `, req.session.userId);
    User.findById(req.session.userId).exec(function(error, user) {
        if (error) {
            return next(error);
        } else {
            if (user === null) {
                var error = new Error('Not authorized! Go back!');
                error.status = 400;
                return next(error);
            } else {
                console.log('Client username check: ' + req.session.userId);
                return res.redirect('http://localhost:8080/finish-registration');
            }
        }
    });
});

// GET for logout logout
router.get('/logout', function(req, res, next) {
    if (req.session) {
        // delete session object
        req.session.destroy(function(err) {
            if (err) {
                return next(err);
            } else {
                return res.redirect('/');
            }
        });
    }
});

module.exports = router;

模型/ user.js的

var mongoose = require('mongoose');
var bcrypt = require('bcrypt');

var UserSchema = new mongoose.Schema({
    email: {
        type: String,
        unique: true,
        required: true,
        trim: true
    },
    password: {
        type: String,
        required: true
    },
    confirmPassword: {
        type: String,
        required: true
    },
    registrationFinished: {
        type: Boolean,
        required: false
    }
});

// authenticate input against database
UserSchema.statics.authenticate = function(email, password, callback) {
    User.findOne({ email: email }).exec(function(err, user) {
        if (err) {
            return callback(err);
        } else if (!user) {
            var err = new Error('User not found');
            err.status = 400;
            return callback(err);
        }

        bcrypt.compare(password, user.password, function(err, result) {
            if (result === true) {
                return callback(null, user);
            } else {
                return callback();
            }
        });
    });
};

// hashing a password before saving it to the database
UserSchema.pre('save', function(next) {
    var user = this;
    console.log(user.email);
    bcrypt.hash(user.password, 10, function(err, hash) {
        if (err) {
            return next(err);
        }

        user.password = hash;
        next();
    });
});

var User = mongoose.model('User', UserSchema);
module.exports = User;

1 个答案:

答案 0 :(得分:0)

如果有人遇到同样的问题,问题就与axios有关。添加

axios.defaults.withCredentials = true;

做了这个伎俩。另请注意,添加withCredentials: true作为发布请求的选项没有帮助,即这不起作用:

axios
   .post('http://localhost:3000/s', {
        newUserInfo: jsonData,
        withCredentials: true
})