我正在尝试将身份验证有效负载传递给后端api并获取响应代码,而在处理错误响应代码时,它总是未定义。 我们无法识别正确的http错误代码。 在第一个循环中,我能够在
中获得http代码响应catch(function (error) {
reject(console.log("errorin firstcatch", error.response.status));
});
})
但是在授权功能中,错误如未定义而来。
const authMock = (username, password)=>
new Promise((resolve, reject)=>{
let payload ={
username:username,
password:password
}
// const loginToken=generateJwt(payload);
// let headers = {
// "loginToken" : loginToken
// }
axios.post(apiBaseUrl,payload)
.then(function (response){
console.log("status", response.data.status_code);
if(response.status == 200||204){
resolve({token:response.data.access_token,
firstName:response.data.FirstName,
lastName:response.data.LastName,
profilePic: response.data.image})
}
else{
console.log("login rejected")
// reject({ status: 401 });
}
})
.catch(function (error) {
reject(console.log("errorin firstcatch", error.response.status));
});
})
function* authorize({ payload: { username, password } }) {
try {
const { token, firstName, lastName, profilePic } = yield call(authMock, username, password);
yield put({ type: AUTH_SUCCESS, payload: {token, firstName, lastName, profilePic} });
localStorage.setItem('token', token);
localStorage.setItem('firstName', firstName);
localStorage.setItem('lastName', lastName);
localStorage.setItem("profilePic", profilePic);
} catch (error) {
let message;
console.log("error", error);
switch (error) {
case 500: message = 'Internal Server Error'; break;
case 401: message = 'Wrong user ID'; break;
case 403: message = "Invalid credentials"; break;
default: message = "Something went wrong!"; break;
}
yield put({ type: AUTH_FAILURE, payload: message });
localStorage.removeItem('token');
localStorage.removeItem('firstName');
localStorage.removeItem('lastName');
localStorage.removeItem('profilePic');
}
}
function* Saga() {
yield takeLatest(AUTH_REQUEST, authorize);
}
答案 0 :(得分:0)
检查代码的这一部分,可能需要一个小的重构:
axios.post(apiBaseUrl,payload)
.then(function (response){
console.log("status", response.data.status_code);
if(response.status == 200||204){
resolve({
token:response.data.access_token,
firstName:response.data.FirstName,
lastName:response.data.LastName,
profilePic: response.data.image
})
}
}
您错过了GET
POST
编辑的信息的一步:
axios.post(apiBaseUrl, payload)
.then(() => axios.get('URL')) <-- Add another endpoint to get the stored payload
.then((response) => { <-- Now the response should contain the status
console.log("status", response.data.status_code);
if(response.status == 200 || 204){
resolve({
token:response.data.access_token,
firstName:response.data.FirstName,
lastName:response.data.LastName,
profilePic: response.data.image
})
}
}