express---express-session axios
阿新 • • 發佈:2019-04-07
ios mea localhost quest acc defined pass from del
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,…}
express---express-session axios