Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/388.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在Vue中使用axios检索JSON web令牌?_Javascript_Vue.js_Jwt_Bearer Token - Fatal编程技术网

Javascript 如何在Vue中使用axios检索JSON web令牌?

Javascript 如何在Vue中使用axios检索JSON web令牌?,javascript,vue.js,jwt,bearer-token,Javascript,Vue.js,Jwt,Bearer Token,因此,我试图为我的第一个Vue项目创建一个CRUD页面,但我不断出错,无法找到一个好的解决方案或有效的示例 当我通过邮递员发布此请求时: 我从数据库中获得aspected的结果,但当我尝试从vue页面执行此操作时,我似乎无法正确获得结果。我一直收到一个401未经授权的错误,但我想我确实有一个带有令牌的标题 我的vue页面: <template> <div class="list row"> <div class="col-

因此,我试图为我的第一个Vue项目创建一个CRUD页面,但我不断出错,无法找到一个好的解决方案或有效的示例

当我通过邮递员发布此请求时:

我从数据库中获得aspected的结果,但当我尝试从vue页面执行此操作时,我似乎无法正确获得结果。我一直收到一个401未经授权的错误,但我想我确实有一个带有令牌的标题

我的vue页面:

<template>
  <div class="list row">
    <div class="col-md-8">
    </div>
    <div class="col-md-6">
      <h4>Parties List</h4>
      <ul class="list-group">
        <li class="list-group-item"
            :class="{ active: index == currentIndex }"
            v-for="(party, index) in parties"
            :key="index"
            @click="setActiveParty(party, index)"
        >
          {{ party.name }}
        </li>
      </ul>

      <button class="m-3 btn btn-sm btn-danger" @click="removeAllParties">
        Remove All
      </button>
    </div>
    <div class="col-md-6">
      <div v-if="currentParty">
        <h4>Party</h4>
        <div>
          <label><strong>Title:</strong></label> {{ currentParty.name }}
        </div>
        <div>
          <label><strong>Description:</strong></label> {{ currentParty.description }}
        </div>
        <div>
          <label><strong>Is party national:</strong></label> {{ currentParty.ispartynational ? "Yes" : "No" }}
        </div>
        <div>
          <label><strong>partyLeader:</strong></label> {{ currentParty.partyLeader.name}}
        </div>

        <a class="badge badge-warning"
           :href="'/parties/' + currentParty.id"
        >
          Edit
        </a>
      </div>
      <div v-else>
        <br />
        <p>Please click on a Party...</p>
      </div>
    </div>
  </div>
</template>


<script>
import PartyDataService from "@/services/PartyDataService";
export default {
  name: "PartiesList",
  data() {
    return {
      parties: [],
      currentParty: null,
      currentIndex: -1,
      name: ""
    };
  },
  methods: {
    retrieveParties() {
      PartyDataService.getAll()
          .then(response => {
            this.parties = response.data;
            console.log(response.data);

          })
          .catch(e => {
            console.log(e);
          });
    },

    refreshList() {
      this.retrieveParties();
      this.currentParty = null;
      this.currentIndex = -1;
    },

    setActiveParty(party, index) {
      this.currentParty = party;
      this.currentIndex = index;
    },

    removeAllParties() {
      PartyDataService.deleteAll()
          .then(response => {
            console.log(response.data);
            this.refreshList();
          })
          .catch(e => {
            console.log(e);
          });
    },
    searchName() {
      PartyDataService.findByName(this.name)
          .then(response => {
            this.tutorials = response.data;
            console.log(response.data);
          })
          .catch(e => {
            console.log(e);
          });
    }
  },

  mounted() {
    this.retrieveParties();
  }
};

</script>

<style>
.list {
  text-align: left;
  max-width: 750px;
  margin: auto;
}
</style>
import http from "../http-common";

class PartyDataService {
    getAll() {
        return http.get("/parties");

    }

    get(id) {
        return http.get(`/parties/${id}`);
    }

    create(data) {
        return http.post("/parties/", data);
    }

    update(id, data) {
        return http.put(`/parties/${id}`, data);
    }

    delete(id) {
        return http.delete(`/parties/${id}`);
    }

    deleteAll() {
        return http.delete(`/parties`);
    }
    findByName(name){
        return http.get(`/parties/${name}`)
    }
}

export default new PartyDataService();
import axios from "axios";

export default axios.create({
    baseURL: "http://localhost:8080/",
    headers: {

         "Content-type": "application/json"
    }

});
我的Http公用:

<template>
  <div class="list row">
    <div class="col-md-8">
    </div>
    <div class="col-md-6">
      <h4>Parties List</h4>
      <ul class="list-group">
        <li class="list-group-item"
            :class="{ active: index == currentIndex }"
            v-for="(party, index) in parties"
            :key="index"
            @click="setActiveParty(party, index)"
        >
          {{ party.name }}
        </li>
      </ul>

      <button class="m-3 btn btn-sm btn-danger" @click="removeAllParties">
        Remove All
      </button>
    </div>
    <div class="col-md-6">
      <div v-if="currentParty">
        <h4>Party</h4>
        <div>
          <label><strong>Title:</strong></label> {{ currentParty.name }}
        </div>
        <div>
          <label><strong>Description:</strong></label> {{ currentParty.description }}
        </div>
        <div>
          <label><strong>Is party national:</strong></label> {{ currentParty.ispartynational ? "Yes" : "No" }}
        </div>
        <div>
          <label><strong>partyLeader:</strong></label> {{ currentParty.partyLeader.name}}
        </div>

        <a class="badge badge-warning"
           :href="'/parties/' + currentParty.id"
        >
          Edit
        </a>
      </div>
      <div v-else>
        <br />
        <p>Please click on a Party...</p>
      </div>
    </div>
  </div>
</template>


<script>
import PartyDataService from "@/services/PartyDataService";
export default {
  name: "PartiesList",
  data() {
    return {
      parties: [],
      currentParty: null,
      currentIndex: -1,
      name: ""
    };
  },
  methods: {
    retrieveParties() {
      PartyDataService.getAll()
          .then(response => {
            this.parties = response.data;
            console.log(response.data);

          })
          .catch(e => {
            console.log(e);
          });
    },

    refreshList() {
      this.retrieveParties();
      this.currentParty = null;
      this.currentIndex = -1;
    },

    setActiveParty(party, index) {
      this.currentParty = party;
      this.currentIndex = index;
    },

    removeAllParties() {
      PartyDataService.deleteAll()
          .then(response => {
            console.log(response.data);
            this.refreshList();
          })
          .catch(e => {
            console.log(e);
          });
    },
    searchName() {
      PartyDataService.findByName(this.name)
          .then(response => {
            this.tutorials = response.data;
            console.log(response.data);
          })
          .catch(e => {
            console.log(e);
          });
    }
  },

  mounted() {
    this.retrieveParties();
  }
};

</script>

<style>
.list {
  text-align: left;
  max-width: 750px;
  margin: auto;
}
</style>
import http from "../http-common";

class PartyDataService {
    getAll() {
        return http.get("/parties");

    }

    get(id) {
        return http.get(`/parties/${id}`);
    }

    create(data) {
        return http.post("/parties/", data);
    }

    update(id, data) {
        return http.put(`/parties/${id}`, data);
    }

    delete(id) {
        return http.delete(`/parties/${id}`);
    }

    deleteAll() {
        return http.delete(`/parties`);
    }
    findByName(name){
        return http.get(`/parties/${name}`)
    }
}

export default new PartyDataService();
import axios from "axios";

export default axios.create({
    baseURL: "http://localhost:8080/",
    headers: {

         "Content-type": "application/json"
    }

});
我尝试在http-common.js文件中执行此操作:

import axios from "axios";

export default axios.create({
    baseURL: "http://localhost:8080/",
    headers: {
         Authorization: 'Bearer ' + localStorage.getItem('Authorization'),
         "Content-type": "application/json"
    }

});
但这给了我同样的错误,加上一个额外的cors错误,当我不包括那行代码时,我没有这个错误

我不知道将代码行放在哪里(我认为这将帮助我解决问题)。有人能帮我吗?
提前谢谢

根据邮递员请求的屏幕截图和共享的代码片段,授权值似乎不匹配

邮递员中的its:
承载人:您的授权令牌

在axios头文件中,其:
承载您的授权令牌

Bearer
后面的冒号可能就是这里的问题

另外,不要直接在
axios.create中设置授权标头。而是创建一个axios实例,在请求obj上使用axios拦截器,并在那里设置身份验证令牌。因为您的身份验证令牌可能会过期,并且当您刷新令牌时,axios将不会从本地存储更新新令牌
axios.create
仅在创建实例时运行一次。因此,它将使用最初添加的令牌。但另一方面,每次发出请求时都会调用Axios拦截器,因此它会在每次请求之前从本地存储中获取令牌。这确保您发送的是有效的令牌,而不是过时的令牌。希望能有帮助

import axios from 'axios'
import { BASE_URL } from './constants'

const instance = axios.create({
  baseURL: BASE_URL,
})

instance.interceptors.request.use(
    (config) => {
      const token = localStorage.getItem('Authorization')
      if (token) {
         config.headers.Authorization = `Bearer ${token}`
         config.headers["Content-Type"] = "application/json"
      } else {
         // Do something... Usually logout user.
      }
      return config
    }
)

export default instance

http-common.js应该与上面类似。

根据邮递员请求的屏幕截图和共享的代码片段,授权的值似乎不匹配

邮递员中的its:
承载人:您的授权令牌

在axios头文件中,其:
承载您的授权令牌

Bearer
后面的冒号可能就是这里的问题

另外,不要直接在
axios.create中设置授权标头。而是创建一个axios实例,在请求obj上使用axios拦截器,并在那里设置身份验证令牌。因为您的身份验证令牌可能会过期,并且当您刷新令牌时,axios将不会从本地存储更新新令牌
axios.create
仅在创建实例时运行一次。因此,它将使用最初添加的令牌。但另一方面,每次发出请求时都会调用Axios拦截器,因此它会在每次请求之前从本地存储中获取令牌。这确保您发送的是有效的令牌,而不是过时的令牌。希望能有帮助

import axios from 'axios'
import { BASE_URL } from './constants'

const instance = axios.create({
  baseURL: BASE_URL,
})

instance.interceptors.request.use(
    (config) => {
      const token = localStorage.getItem('Authorization')
      if (token) {
         config.headers.Authorization = `Bearer ${token}`
         config.headers["Content-Type"] = "application/json"
      } else {
         // Do something... Usually logout user.
      }
      return config
    }
)

export default instance

http-common.js应该与上面类似。

您是否尝试过将axios req对象记录到控制台中,并查看headers对象的样子?嘿,我在回答中添加了一些对您有帮助的附加信息。请看一看。您是否尝试过将axios req对象记录到控制台中,并查看headers对象的样子?嘿,我在回答中添加了一些对您有帮助的附加信息。请看一看。你有一个例子的链接吗?查看james ace的答案。这是正确的方法。所以james ace编写的代码应该在我的http公共文件中。我已经在答案中添加了实现。您是否有指向示例的链接?查看james ace的答案。这是正确的方法。所以james ace编写的代码应该在我的http公共文件中。我已经在答案中添加了实现。