【问题标题】:How to throw a server error when fetching JS获取JS时如何抛出服务器错误
【发布时间】:2022-01-20 10:30:49
【问题描述】:

我是 JavaScript 新手,我的任务是将电子邮件输入从表单发布到节点服务器,一切正常,但我应该实现此功能:
当电子邮件是禁止@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);

验证函数:

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 }

请帮忙。提前致谢!

【问题讨论】:

    标签: javascript node.js server fetch


    【解决方案1】:

    这样的事情应该可以工作:

    服务器代码:

    简化验证功能。

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

    在您的前端中,您可以使用电子邮件有效负载发布到/订阅

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

    【讨论】:

    • 我看到你的代码和我的没有太大不同,所以我很快就观察到我的错误在哪里。要从服务器获取错误,我必须修改路由,所以我去了我项目中的路由文件,发现没有禁止@gmail.com,但禁止@email.com,所以当我输入表单时,禁止@gmail.com服务器认为它不禁止@email.com。现在一切正常,我从服务器收到错误,在控制台中收到我的自定义错误。谢谢!
    猜你喜欢
    • 2019-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-04
    • 1970-01-01
    • 2012-02-11
    • 1970-01-01
    相关资源
    最近更新 更多