【问题标题】:Vue or Axios don't store session cookieVue 或 Axios 不存储会话 cookie
【发布时间】: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


    【解决方案1】:

    根据我的经验,这往往是由 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 尤为重要,否则攻击者可能会使用跨站点脚本攻击。

    希望对您有所帮助!

    【讨论】:

    • 我已经尝试查看 CORS 问题。但为什么我不明白为什么在邮递员上它可以工作?后端实际上托管在一个域名下,但前端在本地以开发模式(localhost:8080)运行,使用 webpack 我在第一篇文章中在后端添加了 cors 配置。并将尝试您的解决方案
    • Postman 不受 CORS 限制,无论配置如何,都会随请求发送 cookie。对于 cURL 等其他类似工具也是如此。
    • 所以问题出在 axios 上?
    • 不,问题在于您的 API 没有返回 Axios 发送 cookie 所需的 CORS 标头。如果没有标头,Axios 或任何其他 JS HTTP 库都无法发送 cookie。
    • 我已经用您粘贴的代码进行了测试,只是将来源更改为“*”或“localhost”,但我没有更改任何内容
    【解决方案2】:

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

    axios.defaults.withCredentials = true
    

    来自docs

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

    【讨论】:

      猜你喜欢
      • 2019-08-19
      • 2020-11-08
      • 2020-12-26
      • 2014-10-14
      • 2012-02-12
      • 1970-01-01
      • 1970-01-01
      • 2014-11-05
      • 2017-01-09
      相关资源
      最近更新 更多