express---express-session axios
使用axios访问后台获取session中的属性值为undefined
-
在main.js中导入axios
import axios from 'axios' axios.defaults.withCredentials = true//关键 Vue.prototype.$http = axios
-
server.js中编写接口
var express=require('express'); var session = require("express-session"); var cookieParser = require("cookie-parser"); var app =express(); var router = express.Router(); app.use(cookieParser('sessiontest')); app.use(session({ secret: 'sessiontest',//与cookieParser中的一致 resave: true, saveUninitialized:true })); //设置跨域访问,关键 app.all('*', function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With,Content-Type"); res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS"); //res.header("X-Powered-By",' 3.2.1'); //res.header("Content-Type", "application/json;charset=utf-8"); next(); }); app.use(router) router.get('/getUserByNameAndPass',function(req,res){//get请求 var sql = "select * from userInfo where account = ?"; connection.query(sql,req.query.account, function (error, data) { if (error) { var result = { "status": "500", "message": "服务器错误" } return res.jsonp(result); }else{ if (data.length == 0) { res.jsonp({ "status": "200","message": "账号不存在",}); }else if(data[0].password != req.query.password){ res.jsonp({ "status": "200","message": "密码错误",}); }else{ req.session.userInfo = data[0] res.send({ "status": "200","message": "success",'user':data[0]}); } } }) }) router.post('/loginUserInfo',function(req,res){ if(req.session.userInfo){ res.jsonp({ "status": "200","message": "success",'userInfo':req.session.userInfo}); }else{ res.jsonp({ "status": "200","message": "error",'message':"用户未登录"}); } })
-
axios访问接口
getUserByNameAndPass () { this.$http({ method: 'get', url: 'http://localhost:8283/getUserByNameAndPass', params: { 'password': '12138', 'account': 'fc6963', } }).then(function (res) { console.log(res) }) }, loginUserInfo () { this.$http({ method: 'post', url: 'http://localhost:8283/loginUserInfo', }).then(function (res) { console.log(res) }) }, //loginUserInfo方法收到从server响应session中的数据 {id: 1, name: "付xx", account: "fc6963", age: 29, identify: "管理员", password: "12138", phoneNumber: null,…}