我正在使用Vue @ CLI和ExpressJs和Passport.js进行身份验证。我编写了以下代码,用于设置使用电子邮件和密码进行身份验证的本地策略。我已经在邮递员中测试了代码,并且工作正常,cookie已成功存储到会话中。
但是,当我从客户端(即VueJs)获取Http请求时,它存储了会话,但是当我刷新浏览器时,该会话消失了。我
我只是Web开发的初学者,我已经尝试了Internet上提供的所有解决方案,例如使用axios.defaults.withCredentials = true并在请求中传递withCredentials:true。
请帮助我,我被封锁了。...
users.js
router.post('/login', async (req, res, next) => { passport.authenticate('local', { session: false }, (err, user, info) => { if(err) return next(err) if (!user) { return res.send("LogIn Failed") } req.logIn(user, function(err) { if (err) { return next(err) } req.session.user = "hey" console.log(req.session) res.send("Log In Success") }) })(req, res, next)router.post('/login', async (req, res, next) => { passport.authenticate('local', { session: false }, (err, user, info) => { if(err) return next(err) if (!user) { return res.send("LogIn Failed") } req.logIn(user, function(err) { if (err) { return next(err) } req.session.user = "hey" console.log(req.session) res.send("Log In Success") }) })(req, res, next) })
app.js
const express = require('express')
const app = express()
const morgan = require('morgan')
const bodyParser = require('body-parser')
const mongoose = require('mongoose')
const session = require('express-session')
const passport = require('passport')
const cors = require('cors')
const MongoStore = require('connect-mongo')(session);
const cookieParser = require('cookie-parser')
//Config Passport
require('./config/passport')(passport)
//Routes
const projectRoutes = require('./api/routes/projects')
const userRoutes = require('./api/routes/users')
//App Middlewares
app.use(morgan('dev'))
app.use(cors())
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use(cookieParser())
//Express Session
app.use(session({
secret: 'secret-key',
resave: false,
saveUninitialized: true,
store: new MongoStore({
mongooseConnection: mongoose.connection,
ttl: 24 * 60 * 60
}),
cookie: {
maxAge: 24 * 60 * 60 * 1000
}
}))
//Passport Middleware
app.use(passport.initialize());
app.use(passport.session());
//Route Middlewares
app.use('/project', projectRoutes)
app.use('/user', userRoutes)
//404 Not Found
app.use((req, res, next) => {
const error = new Error('Not Found')
error.status = 404
next(error)
})
//Errors
app.use((error, req, res, next) => {
res.status(error.status || 500)
res.json({
error: {
message: error.message
}
})
})
//Database Connection
mongoose.connect('mongodb://localhost/database', { useNewUrlParser: true },)
// mongoose.Promise = global.Promise;
module.exports = app
并且我正在传递以下请求:
this.result = await axios.post('http://localhost:3000/user/login', {
email: this.email,
password: this.password
},
{withCredentials: true});
答案 0 :(得分:0)
只需将app.use(cors())
更改为
app.use(cors(
{origin: ['your client side server'],
methods: ['GET', 'POST'],
credentials:true,
}
))