Given 是一個用于管理用戶的應用程式。以下幫助檔案用于此目的:
- AuthenticationAction.js
- ManagementAction.js
AuthenticationAction.js 用于身份驗證:
export function authenticateUser(userID, password) {
console.log("Authenticate")
return dispatch => {
dispatch(getAuthenticateUserPendingAction());
login(userID, password).then(userSession => {
const action = getAuthenticationSuccessAction(userSession);
dispatch(action);
}, error => {
dispatch(getAuthenticationErrorAction(error));
}).catch(error => {
dispatch(getAuthenticationErrorAction(error));
})
}
}
function login(userID, password) {
const hash = Buffer.from(`${userID}:${password}`).toString('base64')
const requestOptions = {
method: 'POST',
headers: {
'Authorization': `Basic ${hash}`
},
};
return fetch('https://localhost:443/authenticate', requestOptions)
.then(handleResponse)
.then(userSession => {
return userSession;
});
}
function handleResponse(response) {
console.log(response)
const authorizationHeader = response.headers.get('Authorization');
return response.text().then(text => {
if (authorizationHeader) {
var token = authorizationHeader.split(" ")[1];
}
if (!response.ok) {
if (response.status === 401) {
logout();
}
const error = response.statusText;
return Promise.reject(error);
} else {
let userSession = {
/* user: data, */
accessToken: token
}
return userSession;
}
});
}
ManagementAction.js 用于 Crud 函式。
export function createUser(userID, username, password) {
console.log("Create a User")
return dispatch => {
dispatch(getShowUserManagementAction());
createaUser(userID, username, password).then(userSession => {
const action = getShowUserManagementActionSuccess(userSession);
dispatch(action);
}, error => { dispatch(getShowUserManagementErrorAction(error)); }).catch(error => { dispatch(getShowUserManagementErrorAction(error)); })
}
}
function createaUser(userID, username, password) {
const token = "whatever"
const requestOptions = {
method: 'POST',
headers: { 'Authorization': `Basic ${token}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ userID: userID, userName: username, password: password })
};
console.log(requestOptions)
return fetch('https://localhost:443/user/', requestOptions)
.then(handleResponse)
.then(userSession => {
return userSession;
});
}
問題:
現在,如果我想使用該createaUser函式而不是硬編碼的令牌值和我在其中創建的訪問令牌,我login如何獲取訪問令牌以及如何重寫該createaUser函式?
uj5u.com熱心網友回復:
您可以將創建的令牌存盤在本地存盤中,如下所示:
AuthenticationAction.js
let userSession = {
/* user: data, */
accessToken: token
}
localStorage.setItem("token", userSession.accessToken)
您可以按如下方式訪問它:
ManagementAction.js
function createaUser(userID, username, password) {
const token = localStorage.getItem("token")
const requestOptions = {
method: 'POST',
headers: { 'Authorization': `Basic ${token}`, 'Content-Type': 'application/json' },
then
這樣您就可以在請求中發送您的令牌值
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/410587.html
標籤:
