如何在Vue中使用axios获取JSON Web Token?
如何在Vue中使用axios获取JSON Web Token?
我正在尝试为我的第一个Vue项目制作一个CRUD页面,但是我一直遇到错误,无法找到一个适用的解决方案或示例。
当我通过Postman发送这个请求时:
我得到了我期望的从数据库中获取的结果,但是当我尝试从我的Vue页面执行此操作时,我似乎无法搞定。我一直收到401未授权错误,但是我认为我确实有一个带有令牌的头部。
我的Vue页面:
派对列表
- {{ party.name }}
派对
{{ currentParty.name }} {{ currentParty.description }} {{ currentParty.ispartynational ? "是" : "否" }} {{ currentParty.partyLeader.name}} 编辑 请点击一个派对...
我的PartyDataService:
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();
我的Http-common:
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" } });
但是这给了我相同的错误以及额外的跨域错误,如果我不包含那行代码就没有这个错误。
我不知道在哪里放置这行代码(我认为这会帮助我解决问题)。有人可以帮助我吗?
提前谢谢!
问题的原因是在使用axios发送请求时,Authorization头部的值没有正确设置。在postman中,Authorization值为Bearer: your_auth_token
,而在axios的headers中,Authorization值为Bearer your_auth_token
。这里的冒号可能就是问题所在。
解决方法是不要直接在axios.create
中设置authorization头部。而是创建一个axios实例,并在请求对象上使用axios拦截器设置auth token。因为auth token可能会过期,当刷新token时,axios不会从本地存储中更新新的token。而axios.create
只在实例创建时运行一次,所以它会使用最初添加的token。但是,Axios拦截器在每次发出请求时都会被调用,因此它会在每个请求之前从本地存储中获取token。这样可以确保发送有效的token而不是过时的token。
整理后的代码如下:
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应该类似于上面的代码。
你有一个示例链接吗?可以参考stackoverflow.com/questions/43051291/…,查看james ace的答案,这是正确的方法。
所以,james ace的代码应该放在我的http-common文件中。
没错。我已经将实现添加到答案中了。