首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >令牌丢失在我的vue应用程序中

令牌丢失在我的vue应用程序中
EN

Stack Overflow用户
提问于 2018-03-16 21:04:34
回答 2查看 1.1K关注 0票数 0

当用户被记录时,我在海蒂派中得到了这个响应:

代码语言:javascript
复制
chat-api$ http :3000/signup username=tomatito password=123
HTTP/1.1 201 Created
Cache-Control: max-age=0, private, must-revalidate
Content-Type: application/json; charset=utf-8
ETag: W/"01dfe24bd7415e252b5aee50e12198a3"
Transfer-Encoding: chunked
Vary: Origin
X-Request-Id: a095148b-592a-4347-820f-63e1efa0e409
X-Runtime: 0.347726

{
    "auth_token": "eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjo1LCJleHAiOjE1MjEzMTg4NDV9.45JDA7vk-K8gUzCB1xABKMifi-IWGoVESedKykGiqGo", 
    "message": "Account created successfully"
}

对象被持久化在我的数据库中。

然而,当我使用来自vue.js表单的axios提出这个请求时,我在localStorage中什么也没有得到。

这是我的axios.js代码:

代码语言:javascript
复制
import axios from 'axios'
const API_URL = process.env.API_URL || 'http://localhost:3000/'

export default axios.create({
  baseURL: API_URL,
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer ' + localStorage.auth_token
  }
})

对象保持在数据库中,但我得到了Authorization:Bearer undefined

这些是我的标题:响应:

代码语言:javascript
复制
Access-Control-Allow-Methods:GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD
Access-Control-Allow-Origin:http://localhost:8081
Access-Control-Expose-Headers:
Access-Control-Max-Age:1728000
Cache-Control:max-age=0, private, must-revalidate
Content-Type:application/json; charset=utf-8
ETag:W/"fdac439f3ada9e343d0815bb49dff277"
Transfer-Encoding:chunked
Vary:Origin
X-Request-Id:9e318050-ceca-480c-a847-d59f9ebb18b7
X-Runtime:0.447976

请求:

代码语言:javascript
复制
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.9
Authorization:Bearer undefined
Connection:keep-alive
Content-Length:44
Content-Type:application/json
Host:localhost:3000
Origin:http://localhost:8081
Referer:http://localhost:8081/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.75 Safari/537.

请求有效载荷

代码语言:javascript
复制
{username: "tomatito", password: "123456"}
password:"123456"username:"tomatito"

这是我的vue脚本组件:

代码语言:javascript
复制
<script>
export default {
  name: 'SignUp',
  data () {
    return {
      username: '',
      password: '',
      error: false
    }
  },
  methods: {
    signup () {
      this.$http.post('/signup', { username: this.username, password: this.password })
      .then(request => this.signupSuccessful(request))
      .catch(() => this.signupFailed())
    },
    signupSuccessful (req) {
      if (!req.data.token) {
        this.signupFailed()
        return
      }
      localStorage.token = req.data.token
      this.error = false
      this.$router.replace(this.$route.query.redirect || '/rooms')
    },
    signupFailed () {
      this.error = 'Sign up failed!'
      delete localStorage.token
    }
  }
}
</script>

我正在让注册失败的,但是对象被持久化在数据库中。我的后端是红宝石铁轨。如何在有效载荷下在data.token中接收?

这是我的main.js文件

代码语言:javascript
复制
import Vue from 'vue'
import App from './App'
import router from './router'
import axios from './backend/vue-axios'

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  axios,
  template: '<App/>'
})

这是我的vue-axios/index.js文件:

代码语言:javascript
复制
import Vue from 'vue'
import VueAxios from 'vue-axios'

import axios from './axios'

Vue.use(VueAxios, axios)

更新了,问题在req中。是res接收令牌,而不是req

代码语言:javascript
复制
signup() {
      this.$http
        .post("/signup", { username: this.username, password: this.password })
        .then(res => this.signupSuccessful(res))
        .catch(() => this.signupFailed());
    },
    signupSuccessful(res) {
      if (!res.data.auth_token) {
        this.signupFailed();
        return;
      }
      this.error = false;
      localStorage.token = res.data.auth_token;
      this.$store.dispatch("login");
      this.$router.replace(this.$route.query.redirect || "/rooms");
    },
    .
    .
    .
    .

谢谢

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-03-17 18:10:23

更新了,问题在req中。是res接收令牌,而不是req

代码语言:javascript
复制
signup() {
      this.$http
        .post("/signup", { username: this.username, password: this.password })
        .then(res => this.signupSuccessful(res))
        .catch(() => this.signupFailed());
    },
    signupSuccessful(res) {
      if (!res.data.auth_token) {
        this.signupFailed();
        return;
      }
      this.error = false;
      localStorage.token = res.data.auth_token;
      this.$store.dispatch("login");
      this.$router.replace(this.$route.query.redirect || "/rooms");
    },
    .
    .
    .
    .
票数 0
EN

Stack Overflow用户

发布于 2018-03-16 21:14:55

尝试用axios.interceptors设置每个请求的令牌

将其放在main.js文件中,以便在导入axios的任何地方都有配置

代码语言:javascript
复制
axios.interceptors.request.use(config => {
 const token= localStorage.getItem('my-token-key') // or where you have the token

 config.headers.common['Authorization'] = 'Bearer ' + token

 // you must return the config or it will not work
 return config
})

我认为问题在于,axios.create实例只执行一次(创建)(然后引用它),而不是每次导入它时,所以如果在创建实例时没有令牌,那么它将无法工作。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49329490

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档