【发布时间】:2017-07-02 11:03:51
【问题描述】:
我遇到了一个问题,但我不知道它在哪里以及为什么。 我有一个基于 express4(nodejs) 的后端 API 我们已经使用护照实现了 Auth。
当我使用邮递员时,我在 /login 上使用 post 登录。它存储一个会话 cookie,并且所有路由现在都可以访问,因为 cookie 没有过期。
但是我的前端基于 VueJS。我使用 Axios 来执行请求。这个要求似乎很好。但任何 cookie 都会被存储,因此浏览器会在登录页面上进行环回。
我尝试过不进行身份验证检查或不一样。但是在邮递员上它可以工作。
Vue 的 main.js:
import Vue from 'vue'
import VueRouter from 'vue-router'
import Axios from 'axios'
Vue.use(VueRouter)
import auth from './utils/auth'
import App from './components/App.vue'
import Login from './components/Login.vue'
import Home from './components/Containers.vue'
require('font-awesome-loader');
function requireAuth (to, from, next) {
if (!auth.checkAuth()) {
next({
path: '/login',
query: { redirect: to.fullPath }
})
} else {
next()
}
}
const router = new VueRouter({
mode: 'history',
routes: [
{ path: '/', name: 'containers', component: Home, beforeEnter: requireAuth },
{ path: '/login', component: Login },
{ path: '/logout',
beforeEnter (to, from, next) {
auth.logout()
next('/')
}}
]
})
new Vue({
el: '#app',
router,
render: h => h(App)
})
还有 auth.js(请求完成的地方)
import axios from 'axios'
import { API_URL } from '../config/app'
export default {
user: {
authenticated: false
},
login (email, pass, cb) {
LoginRequest(email, pass, (res) => {
this.user.authenticated = res.authenticated
if (this.user.authenticated) {
console.log('ok')
if (cb) cb(true)
} else {
console.log('pasok')
if (cb) cb(false)
}
})
},
checkAuth () {
if (getAuth()) {
this.authenticated = true
} else {
this.authenticated = false
}
},
logout (cb) {
this.user.authenticated = false
if (cb) cb()
}
}
function LoginRequest (email, pass, cb) {
axios.post(API_URL + '/api/login', {
email: email,
password: pass
}).then(response => {
if (response.status === 200) {
cb({ authenticated: true })
} else {
cb({ authenticated: false })
}
}, response => {
cb({ authenticated: false })
})
}
function getAuth (cb) {
axios.get(API_URL + '/me').then(response => {
return true
}, response => {
return false
})
}
编辑: 我的 cors 在后端使用:
// allow CORS:
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT$
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With,$
next();
});
谢谢!
【问题讨论】:
标签: node.js session cookies vuejs2 axios