[英]How to integrate getAccessToken with fetch function to load data from DRF backend to React Frontend?
在這里反應新手,但精通 Django。我有一個簡單的 fetch 功能,它運行良好,但我的項目沒有涉及登錄身份驗證。 現在我已經配置了登錄系統,我的后端拒絕使用任何訪問令牌來處理請求。 我的登錄身份驗證對我來說很陌生,或多或少是從某個地方復制過來的。 我試圖理解它,但無法理解。 我只需要知道如何將我的簡單 fetch 函數轉換為將 getAccessToken 包含在請求的標頭中,以便我的后端為該請求提供服務。
這是我以前工作的簡單獲取功能:
class all_orders extends Component {
state = {
todos: []
};
async componentDidMount() {
try {
const res = await fetch('http://127.0.0.1:8000/api/allorders/'); // fetching the data from api, before the page loaded
const todos = await res.json();
console.log(todos);
this.setState({
todos
});
} catch (e) {
console.log(e);
}
}
我的新登錄 JWT 身份驗證系統運行良好,但我以前的代碼不起作用並且我不斷收到錯誤消息
"detail": "未提供身份驗證憑據。"
這是我無法與我以前的獲取功能“結合”的訪問令牌:
const getAccessToken = () => {
return new Promise(async (resolve, reject) => {
const data = reactLocalStorage.getObject(API_TOKENS);
if (!data)
return resolve('No User found');
let access_token = '';
const expires = new Date(data.expires * 1000);
const currentTime = new Date();
if (expires > currentTime) {
access_token = data.tokens.access;
} else {
try {
const new_token = await loadOpenUrl(REFRESH_ACCESS_TOKEN, {
method: 'post',
data: {
refresh: data.tokens.refresh,
}
});
access_token = new_token.access;
const expires = new_token.expires;
reactLocalStorage.setObject(API_TOKENS, {
tokens: {
...data.tokens,
access: access_token
},
expires: expires
});
} catch (e) {
try {
if (e.data.code === "token_not_valid")
signINAgainNotification();
else
errorGettingUserInfoNotification();
} catch (e) {
// pass
}
return reject('Error refreshing token', e);
}
}
return resolve(access_token);
});
};
如果您正在尋找一種如何在 fetch 請求中傳遞標頭的方法,它非常簡單:
await fetch('http://127.0.0.1:8000/api/allorders/', {
headers: {
// your headers there as pair key-value, matching what your API is expecting, for example:
'details': getAccessToken()
}
})
只是不要忘記導入您的 getAccessToken const,如果將其放在另一個文件中,我相信就是這樣。 關於 Fetch 方法的一些閱讀
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.