[英]How to throw a server error when fetching JS
我是 JavaScript 的新手,我的任务是将 email 输入从表单发布到节点服务器,一切正常,但我应该实现此功能:
当 email 被禁止@gmail.com 时,服务器会以 422 状态码和包含有关错误信息的有效负载进行响应。 使用浏览器开发人员工具检查此场景的响应。 使用 window.alert() 在浏览器中显示错误消息。
我创建了一个 customException,它在控制台中给了我错误,但服务器仍然响应 200 状态代码,但据我了解,它应该给出一个错误并且帖子不应该工作。如何执行此任务,我有不知道..?
获取功能:
import { validateEmail } from './email-validator.js'
export const sendSubscribe = (emailInput) => {
const isValidEmail = validateEmail(emailInput)
if (isValidEmail === true) {
sendData(emailInput);
// if (emailInput === 'forbidden@gmail.com'){
// throw new CustomException('422');
// }
}
}
const sendHttpRequest = (method, url, data) => {
return fetch(url, {
method: method,
body: JSON.stringify(data),
headers: data ? {
'Content-Type': 'application/json'
} : {}
}).then(response => {
if (response.status >= 400) {
return response.json().then(errResData => {
const error = new Error('Something went wrong!');
error.data = errResData;
throw error;
});
}
return response.json();
});
};
const sendData = (emailInput) => {
sendHttpRequest('POST', 'http://localhost:8080/subscribe', {
email: emailInput
}).then(responseData => {
console.log(responseData);
}).catch(err => {
console.log(err, err.data);
});
}
function CustomException(message) {
const error = new Error(message);
error.code = "422";
window.alert('Forbidden email,please change it!')
return error;
}
CustomException.prototype = Object.create(Error.prototype);
验证 function:
const VALID_EMAIL_ENDINGS = ['gmail.com', 'outlook.com', 'yandex.ru']
export const validateEmail = (email) => !!VALID_EMAIL_ENDINGS.some(v => email.includes(v))
export { VALID_EMAIL_ENDINGS as validEnding }
请帮助。在此先感谢!
像这样的东西应该工作:
服务器代码:
简化验证 function。
export const isValid = (email) => {
if (email === 'forbidden@gmail.com') {
return false
}
return true
}
然后在你的路线上,像这样,假设 expressjs 在后面。
app.post('/subscribe', (req, res, next) => {
const email = req.body.email
if (!isValid(email)) {
return res.status(433).send('Email is forbidden')
}
return res.status(200).send('Success')
})
在您的前端,您可以使用 email 有效负载发布到 /subscribe
const sendHttpRequest = (method, url, data) => {
return fetch(url, {
method: method,
body: JSON.stringify(data),
headers: data ? {
'Content-Type': 'application/json'
} : {}
})
.then(response => response.json())
};
在您的 sendData 中,您可以捕获错误,就像您正在做的那样
const sendData = (emailInput) => {
sendHttpRequest('POST', 'http://localhost:8080/subscribe', {
email: emailInput
}).then(responseData => {
console.log(responseData);
}).catch(err => {
console.log(err); // Email is forbidden
window.alert('Boo!')
});
}
旁注:在大多数情况下,应避免在 javascript 中进行原型设计。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.