[英]REACT - How to pass a function to an axios api call
我試圖避免重復檢索訪問令牌並將其傳遞給我的 axios api 的部分代碼。
I have created a separate file that contains a function that performs the retrieving of the token but when i pass that function method to axios api, it does not work. 這意味着沒有從 localStorage 中檢索令牌。 我哪里錯了?
我的GET API 方法
import tokenConfig from "./token"
...
_refreshRecords() {
axios
.get("http://localhost:8000/api/accounts/employees_hr/", tokenConfig) <-- PASSING HERE
.then((response) =>
this.setState({
employeesDetail: response.data.results,
})
);
}
我的令牌文件
// GET TOKEN
export default tokenConfig =>{
// Headers
const config = {
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
},
};
// If there token, add to headers config
if (localStorage.getItem("access")) {
config.headers["Authorization"] = `JWT ${localStorage.getItem("access")}`;
}
return config;
};
您忘記在tokenConfig
中執行_refreshRecords
。
考慮使用 Axios 提供的內置攔截器。 我通常在我的 API Axios 實例中執行此操作。
// /services/api/index.js
import Axios from 'axios';
const api = Axios.create({
baseURL: 'http://localhost:8000/api',
timeout: 30000,
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
}
});
api.interceptors.request.use(
config => {
if (localStorage.getItem("access")) {
config.headers.Authorization = `JWT ${localStorage.getItem("access")}`;
}
return config;
},
error => Promise.reject(error)
);
export default api;
要在其他組件中使用它,您可以導入../services/api
並使用它:
import API from '../services/api';
class App extends Component {
_refreshRecords() {
API.get('/accounts/employees_hr/').then(response =>
this.setState({
employeesDetail: response.data.results,
})
);
}
}
您必須執行tokenConfig
function。 否則,您將傳遞 function 而不是get()
function 期望的 object。
axios
.get("http://localhost:8000/api/accounts/employees_hr/", tokenConfig())
.then((response) =>
this.setState({
employeesDetail: response.data.results,
})
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.