我正在創建一個 MERN 應用程式并設定一個錯誤處理函式,該函式在不滿足某些條件時顯示錯誤訊息。就我而言,我有一個注冊頁面,要求電子郵件有效,密碼至少為 6 個字符。現在,這些訊息在 VS Code 中的后端控制臺上準確顯示,但我無法在瀏覽器/前端的控制臺上顯示它們。我查看了這篇SO 帖子,但仍然無法解決我的問題。我懷疑這是因為我的前端和后端位于不同的埠上,但我仍然不知道如何修復它。代碼貼在下面。
路線代碼
const handleErrors = (err) => {
console.log(err.message, err.code);
let errors = { email: '', password: ''};
//duplicate error code
if(err.code === 11000){
errors.email = "that email is already registered";
}
//Just a way to create custom error messages
if(err.message.includes("Creator validation failed")){
Object.values(err.errors).forEach(({properties}) => {
errors[properties.path] = properties.message;
});
}
return errors;
}
const maxAge = 3 * 24 * 60 * 60;
const createToken = (id) => {
return jwt.sign({ id }, 'efrgvwrtgr435f345secret', {
expiresIn: maxAge
});
}
router.route('/add').post((req,res) => {
const firstName = req.body.firstName;
const lastName = req.body.lastName;
const bio = req.body.bio;
const creatorName = req.body.creatorName;
const password = req.body.password;
const email = req.body.email;
const newCreator = new Creator({firstName, lastName, bio, creatorName, password, email})
newCreator.save()
.then(() => {
const token = createToken(newCreator._id);
res.cookie('jwt', token, { httpOnly: true, maxAge: maxAge * 1000}).json("Token is " token);
// res.json("New creator added!");
res.send("New creator added!");
})
// .catch((err) => { const errors = handleErrors(err); res.status(404).json({ errors })});
.catch((err) => { const errors = handleErrors(err); res.status(404).send({ errors })});
})
從注冊頁面提交操作代碼
const handleSubmit = (e) => {
e.preventDefault()
const creator = {
firstName: firstName,
lastName: lastName,
creatorName: creatorName,
bio: bio,
creatorName: creatorName,
password: password,
email: email
}
console.log(creator);
//If there are any errors when the submit btn was clicked, I want those errors to be displayed on the browser's console
try {
axios.post('http://localhost:5000/creators/add', creator, {withCredentials:true}) //Goes to the server('http://localhost:5000/creators/add')
// .then((res) => console.log(res.data))
.then((res) => console.log(res.json));
history.push('/marketplace');
}
catch (err) {
console.log(err);
}
}
uj5u.com熱心網友回復:
當您發送回應時,res.status(404).send({ errors })您可以告訴客戶端錯誤代碼 - Axios 有一種方法可以捕獲所有不在 200(OK)范圍內的代碼。本質上,如果錯誤代碼隨回應一起發送,您可以使用以下命令查看錯誤資料error.response.data:
axios.post('http://localhost:5000/creators/add', creator, {withCredentials:true}) //Goes to the server('http://localhost:5000/creators/add')
.then((res) => console.log(res.json))
.catch((error) => {
if(error.response) console.log(error.response.data);
})
來源:https ://axios-http.com/docs/handling_errors
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/456746.html
上一篇:郵遞員無法發送請求正文以表達申請
