백엔드에서 Axios를 사용하는 데 문제가 있습니다. 내가 이것을 처음 접했기 때문에 아마도 매우 간단한 수정 일 것입니다.
Postman : 유효한 자격 증명과 유효하지 않은 자격 증명 모두에 대해 올바른 응답이 수신됩니다.
Axios : 유효한 자격 증명에 대해 올바른 응답이 수신되지만 잘못된 자격 증명이 입력되면 axios 메서드의 catch 블록이 실행됩니다.
authController.js :
exports.login = (req, res, next) => {
const email = req.body.email;
const pass = req.body.password;
let loadedUser;
User.findOne({ where: { email: email } })
.then(user => {
if(!user) {
const error = new Error('Incorrect username or password');
error.statusCode = 401;
throw error;
} else {
loadedUser = user;
return bcrypt.compare(pass, user.password);
}
})
.then(isEqual => {
if(!isEqual) {
const error = new Error('Incorrect username or password');
error.statusCode = 401;
throw error;
} else {
const token = jwt.sign(
{
email: loadedUser.email,
userId: loadedUser.id
},
process.env.JWT_SECRET,
{ expiresIn: '1hr' }
);
res.status(200).json({ token: token, userId: loadedUser.id });
}
})
.catch(err => {
if (!err.statusCode)
err.statusCode = 500;
next(err);
});
};
app.js의 오류 처리기. axios에서도 잘못된 자격 증명을 입력하면 오류를 올바르게 기록하는 것 같습니다.
app.use((error, req, res, next) => {
const status = error.statusCode || 500;
const message = error.message;
const data = error.data || 'No Data';
console.log(status, message, data);
res.status(status).json({message: message, data: data});
});
하지만 axios catch 블록이 실행되므로 json 메시지를받는 대신 다음 오류가 발생합니다.
login(email, password) {
const headers = {
'Content-Type': 'application/json'
};
const data = JSON.stringify({
email: email,
password: password
});
axios.post('http://127.0.0.1:8080/auth/login', data, { headers })
.then(res => console.log(res))
.catch(err => console.log(err));
}
잘못된 자격 증명에 대한 콘솔의 오류 : 강조 표시된 링크를 클릭하면 "Cannot GET / auth / login"이라는 새 페이지가 열리지 만 분명히 게시 요청을하고 있으며 양식에 게시물을 추가했습니다. 케이스)
내가 놓칠 수있는 아이디어가 있습니까?
감사
실제로 코드는 잘 작동하지만 Axios는 상태가 401 인 경우 통화 약속을 거부 합니다 . 상태가 200에서 300 사이이면 약속이 해결됩니다.
이를 처리하는 두 가지 방법이 있습니다.
catch 블록에서 상태를 확인하십시오.
axios.post('http://127.0.0.1:8080/auth/login', data, {
headers
})
.then(res => console.log(res))
.catch(err => {
if (err.response.status === 401) {
//Auth failed
//Call reentry function
return;
}
return console.log(err)
});
또는 validateStatus
옵션을 변경하십시오 .
axios.post('http://127.0.0.1:8080/auth/login', data, {
headers,
validateStatus: function (status) {
return status >= 200 && status < 300 || (status === 401);
},
})
.then(res => console.log(res))
.catch(err => return console.log(err));
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다