Vue或Axios不存储会话cookie

时间:2017-02-14 08:41:52

标签: node.js session cookies vuejs2 axios

我遇到了问题,但我不知道它在哪里以及为什么。 我有一个基于express4(nodejs)的后端API我们用护照实现了Auth。

当我使用邮递员时,我登录/登录后登录。它存储会话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
  })
}

编辑: 我的角色在后端使用:

 // 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();
        });

谢谢!

2 个答案:

答案 0 :(得分:2)

根据我的经验,这往往是CORS(跨源资源共享)引起的问题。

即如果您的API_URL与您的应用程序的auth.js不在同一个域中,Axios默认情况下将无法发送Cookie。您可以在此处详细了解如何在您的API中使用跨域凭据:https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Access-Control-Allow-Credentials

实际上,您可以使用CORS模块https://www.npmjs.com/package/cors在某些配置中应用必要的标头,类似于服务器端的以下内容:

var express = require('express')
  , cors = require('cors')
  , app = express()

app.use(cors({
    origin: "myapp.io",
    credentials: true
}))

指定运行auth.js脚本的原始URL尤为重要,否则攻击者可能会使用跨站点脚本攻击。

希望这有帮助!

答案 1 :(得分:0)

您还可以全局设置axios凭据:

axios.defaults.withCredentials = true

docs内部:

// `withCredentials` indicates whether or not cross-site Access-Control requests
// should be made using credentials
withCredentials: false, // default