[英]Sending the bearer token with axios
在我的反應應用程序中,我使用axios來執行 REST api 請求。
但它無法隨請求發送授權header。
這是我的代碼:
tokenPayload() {
let config = {
headers: {
'Authorization': 'Bearer ' + validToken()
}
}
Axios.post(
'http://localhost:8000/api/v1/get_token_payloads',
config
)
.then( ( response ) => {
console.log( response )
} )
.catch()
}
這里validToken()
方法將簡單地從瀏覽器存儲中返回令牌。
所有請求都有一個 500 錯誤響應,說明
無法從請求中解析令牌
從后端。
如何在每個請求中發送授權 header? 你會推薦任何其他帶有反應的模塊嗎?
const config = {
headers: { Authorization: `Bearer ${token}` }
};
const bodyParameters = {
key: "value"
};
Axios.post(
'http://localhost:8000/api/v1/get_token_payloads',
bodyParameters,
config
).then(console.log).catch(console.log);
第一個參數是 URL。
第二個是將隨您的請求發送的 JSON 正文。
第三個參數是標題(除其他外)。 這也是 JSON。
這是在 axios 中設置授權令牌的一種獨特方式。 為每個 axios 調用設置配置不是一個好主意,您可以通過以下方式更改默認授權令牌:
import axios from 'axios';
axios.defaults.baseURL = 'http://localhost:1010/'
axios.defaults.headers.common = {'Authorization': `bearer ${token}`}
export default axios;
一些 API 要求將 bearer 寫成 Bearer,所以你可以這樣做:
axios.defaults.headers.common = {'Authorization': `Bearer ${token}`}
現在您不需要為每個 API 調用設置配置。 現在授權令牌設置為每個 axios 調用。
您可以創建一次配置並在任何地方使用它。
const instance = axios.create({
baseURL: 'https://example.com/api/',
timeout: 1000,
headers: {'Authorization': 'Bearer '+token}
});
instance.get('/path')
.then(response => {
return response.data;
})
axios.post
的第二個參數是data
(不是config
)。 config
是第三個參數。 詳情請參閱: https ://github.com/mzabriskie/axios#axiosposturl-data-config
通過使用 Axios 攔截器:
const service = axios.create({
timeout: 20000 // request timeout
});
// request interceptor
service.interceptors.request.use(
config => {
// Do something before request is sent
config.headers["Authorization"] = "bearer " + getToken();
return config;
},
error => {
Promise.reject(error);
}
);
如果您想在標頭中傳遞令牌后獲取一些數據,請嘗試此代碼
const api = 'your api';
const token = JSON.parse(sessionStorage.getItem('data'));
const token = user.data.id; /*take only token and save in token variable*/
axios.get(api , { headers: {"Authorization" : `Bearer ${token}`} })
.then(res => {
console.log(res.data);
.catch((error) => {
console.log(error)
});
這有效,我只需要在我的app.js
中設置一次令牌:
axios.defaults.headers.common = {
'Authorization': 'Bearer ' + token
};
然后我可以在我的組件中發出請求,而無需再次設置標頭。
"axios": "^0.19.0",
以防萬一有人遇到同樣的問題。
這里的問題是當傳遞沒有數據的標頭時,標頭的配置將在有效負載數據中,所以我需要傳遞 null 而不是數據,然后設置標頭的配置。
const config = {
headers: {
"Content-type": "application/json",
"Authorization": `Bearer ${Cookies.get("jwt")}`,
},
};
axios.get(`${BASE_URL}`, null, config)
我使用一個單獨的文件來初始化 axios 實例,同時,我向它添加了攔截器。 然后在每次調用中,攔截器都會為我將令牌添加到請求標頭中。
import axios from 'axios';
import { getToken } from '../hooks/useToken';
const axiosInstance = axios.create({
baseURL: process.env.REACT_APP_BASE_URL,
});
axiosInstance.interceptors.request.use(
(config) => {
const token = getToken();
const auth = token ? `Bearer ${token}` : '';
config.headers.common['Authorization'] = auth;
return config;
},
(error) => Promise.reject(error),
);
export default axiosInstance;
這是我在服務文件中使用它的方式。
import { CancelToken } from 'axios';
import { ToolResponse } from '../types/Tool';
import axiosInstance from './axios';
export const getTools = (cancelToken: CancelToken): Promise<ToolResponse> => {
return axiosInstance.get('tool', { cancelToken });
};
// usetoken 是鈎子,我瘋了
export const useToken = () => {
return JSON.parse(localStorage.getItem('user')).token || ''
}
const token = useToken();
const axiosIntance = axios.create({
baseURL: api,
headers: {
'Authorization':`Bearer ${token}`
}
});
axiosIntance.interceptors.request.use((req) => {
if(token){
req.headers.Authorization = `Bearer ${token}`;
}
return req;
})
您可以在 axios 中使用攔截器:
axios.interceptors.request.use(function (config) {
// Do something before request is sent
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
您可以在此處找到更多信息: https://axios-http.com/docs/interceptors
如果您要發送帶有空數據的發布請求,請記住始終將第二個參數設置為空對象或空字符串,如下例所示。 例如: axios.post('your-end-point-url-here', '', config)
如果您不設置它,axios 將假定您作為第二個參數傳遞的任何內容都是 formData
const config = {
headers: { Authorization: `Bearer ${storage.getToken()}` }
};
axios
.post('http://localhost:8000/api/v1/get_token_payloads', {}, config)
.then(({ data: isData }) => {
console.log(isData);
})
.catch(error => {
console.log(error);
});
您可以嘗試像這樣配置 header:
const headers = {"Content-Type": "text/plain", "x-access-token": token}
您必須提及發布請求的第二個參數主體,即使它是空的,試試這個:
tokenPayload() {
let config = {
headers: {
'Authorization': 'Bearer ' + validToken()
}
}
Axios.post(
'http://localhost:8000/api/v1/get_token_payloads',
// empty body
{},
config
)
.then( (response) => {
console.log(response)
} )
.catch()
}
這也是我所面對的。 你傳遞的令牌不正確。
只需對令牌進行硬編碼並通過,您將獲得正確的響應。 但如果令牌沒有在單引號中傳遞,那么它肯定會失敗。 它必須采用'授權'格式:'Bearer YzE5ZTdiMjVlYzM5NjA2MGJkZTM5NjVlOTQ5YMmQ5ZjMwYjA0YmEzZmZZNNI1MmI4MDJkNQ',其中必須存在Bearer一個空格后,也在單引號內,這非常重要。
var token = "YzE5ZTdiMjVlYzM5NjA2MGJkZTM5NjVlOTQ5YMmQ5ZjMwYjA0YmEzZmZjN2I1MmI4MDJkNQ";
var headers = {
Authorization: "Bearer " + token,
Accept: "application/json, text/plain, */*",
"Content-Type": "application/json"
};
IMP:上面的代碼可以工作但是如果你發布類似的東西:
'授權':'持票人'+ YzE5ZTdiMjVlYzM5NjA2MGJkZTM5NjVlOTQ5YMmQ5ZjMwYjA0YmEzZmZNNII1MmI4MDJkNQ,它會失敗
或-----以下代碼也將失敗,我希望你了解基本的區別
var token = YzE5ZTdiMjVlYzM5NjA2MGJkZTM5NjA0YmEzZmZjN2I1MmI4MDJkNQ;
var headers = {
Authorization: "Bearer " + token,
Accept: "application/json, text/plain, */*",
"Content-Type": "application/json"
};
axios
本身帶有兩個有用的“方法” interceptors
,它們只是請求和響應之間的中間件。 所以如果你想在每個請求中發送令牌。 使用interceptor.request
。
我做了一個可以幫助你的包:
$ npm i axios-es6-class
現在您可以將 axios 用作類
export class UserApi extends Api {
constructor (config) {
super(config);
// this middleware is been called right before the http request is made.
this.interceptors.request.use(param => {
return {
...param,
defaults: {
headers: {
...param.headers,
"Authorization": `Bearer ${this.getToken()}`
},
}
}
});
this.login = this.login.bind(this);
this.getSome = this.getSome.bind(this);
}
login (credentials) {
return this.post("/end-point", {...credentials})
.then(response => this.setToken(response.data))
.catch(this.error);
}
getSome () {
return this.get("/end-point")
.then(this.success)
.catch(this.error);
}
}
我的意思是middleware
的實現取決於你,或者如果你更喜歡創建自己的axios-es6-class
https://medium.com/@enetoOlveda/how-to-use-axios-typescript-like-a-pro -7c882f71e34a這是它來自的中型帖子
有很多好的解決方案,但我用這個
let token=localStorage.getItem("token");
var myAxios=axios.create({
baseURL: 'https://localhost:5001',
timeout: 700,
headers: {'Authorization': `bearer ${token}`}
});
export default myAxios;
然后我將 myaxios 導入我的文件並
myAxios.get("sth")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.