我的服务器端有ExpressJS,前端有Vue。我想保存会话,但我不能用Vue前端做到这一点。我找不到这个/服务器端的解决方案是:
let express = require('express');
let path = require('path');
let favicon = require('serve-favicon');
let logger = require('morgan');
let cookieParser = require('cookie-parser');
let bodyParser = require('body-parser');
var session = require('express-session')
// const MongoStore = require('connect-mongo')(express_session);
let index = require('./src/routes/index');
let users = require('./src/routes/users');
let gallery = require('./src/routes/gallery')
let auth = require('./src/routes/auth')
let contacts = require('./src/routes/contacts')
let services = require('./src/routes/services')
let cors = require('cors')
let app = express();
app.use(cors({
origin:['http://localhost:8080'],
methods:['GET','POST'],
credentials: true // enable set cookie
}))
let mongoose = require('mongoose')
let express_session = require("express-session");
const MongoStore = require('connect-mongo')(express_session);
//авторизация
app.use(session({
secret: 'keyboard',
resave: false,
saveUninitialized: true,
store: new MongoStore({
url: 'mongodb://localhost/studio'
})
}))
let mongoDB = 'mongodb://127.0.0.1/studio';
mongoose.connect(mongoDB, {
useMongoClient: true
});
let db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
//app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/users', users);
app.use('/gallery', gallery );
app.use('/contacts', contacts );
app.use('/auth', auth);
app.use('/services', services );
//Авторизация в данной система
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
//app.listen(3002);
module.exports = app;
我在mongoose中保存会话,当我检查服务器端会话正在工作时。但是当我想在Vue端保存会话时,它不起作用。我认为这是因为cors,但它没有帮助。 这里的代码:
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<h2>Essential Links</h2>
<ul>
<li><a href="https://vuejs.org" target="_blank">Core Docs</a></li>
<li><a href="https://forum.vuejs.org" target="_blank">Forum</a></li>
<li><a href="https://chat.vuejs.org" target="_blank">Community Chat</a></li>
<li><a href="https://twitter.com/vuejs" target="_blank">Twitter</a></li>
<br>
<li><a href="http://vuejs-templates.github.io/webpack/" target="_blank">Docs for This Template</a></li>
</ul>
<h2>Ecosystem</h2>
<ul>
<li><a href="http://router.vuejs.org/" target="_blank">vue-router</a></li>
<li><a href="http://vuex.vuejs.org/" target="_blank">vuex</a></li>
<li><a href="http://vue-loader.vuejs.org/" target="_blank">vue-loader</a></li>
<li><a href="https://github.com/vuejs/awesome-vue" target="_blank">awesome-vue</a></li>
</ul>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data () {
return {
msg: 'Welcome to Your Vue.js App',
page_views:undefined,
}
},
beforeMount(){
this.$http.get("http://localhost:8120/").then((res)=>{
if(!res.body.session){
console.log("Session not exist "+res.body.message)
this.msg = res.body.message;
}
else{
console.log("Session exist "+res.body.page_views)
this.msg = res.body.page_views
}
},(err)=>{
console.log(err)
})
}
}
</script>
这里的端点代码是:
var express = require('express');
var router = express.Router();
let cors = require('cors')
router.use(cors())
/* GET home page. */
router.get('/', function(req, res){
if(req.session.page_views){
req.session.page_views++;
res.json({session:true,page_views:req.session.page_views});
} else {
req.session.page_views = 1;
res.json({session:false, message:"Welcome to this page for the first time!"})
}
});
module.exports = router;
答案 0 :(得分:1)
你的后端代码没问题,你知道要设置
#include( "header.vel" )
your template code....
#include( "footer.vel" )
以避免(同源政策)。
但我认为前端也需要设置凭证。
你可以试试这个:
credentials: true // enable set cookie
这意味着允许浏览器向后端发送cookie 祝好运!