如何在获取 JS 时抛出服务器错误

How to throw a server error when fetching JS

我是 JavaScript 的新手,我的任务是 post 从表单向节点服务器输入电子邮件,一切正常,但我应该实现此功能:
当电子邮件被禁止@gmail.com 时,服务器会返回 422 状态代码和包含有关错误信息的负载。使用浏览器开发人员工具检查此场景的响应。使用 window.alert().
在浏览器中显示错误消息 我创建了一个 customException,它在控制台中给出了错误,但服务器仍然以 200 状态代码响应,但据我所知,它应该给出一个错误并且 post 不应该 work.How做这个任务,我不知道..?
获取函数:

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);

验证函数:

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 }

请提前help.Thanks!

像这样的东西应该可以工作:

服务器代码:

简化验证功能。

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')
})

在您的前端中,您可以post使用电子邮件负载

/订阅
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 中进行原型设计。