简体   繁体   English

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

[英]How to throw a server error when fetching JS

I'm new in JavaScript and i have a task to post an email input from form to a node server,everything works fine,but i should implement this functionality:我是 JavaScript 的新手,我的任务是将 email 输入从表单发布到节点服务器,一切正常,但我应该实现此功能:
When an email is forbidden@gmail.com, the server responds with the 422 status code and payload which contains the information about the error.当 email 被禁止@gmail.com 时,服务器会以 422 状态码和包含有关错误信息的有效负载进行响应。 Use browser developer tools to examine the response for this scenario.使用浏览器开发人员工具检查此场景的响应。 Display the error message in the browser using window.alert().使用 window.alert() 在浏览器中显示错误消息。
I created a customException,it gives me the error in the console,but the server still responds with the 200 status code,but as i understand,it should give an error and the post should not work.How to do this task,i have no idea..?我创建了一个 customException,它在控制台中给了我错误,但服务器仍然响应 200 状态代码,但据我了解,它应该给出一个错误并且帖子不应该工作。如何执行此任务,我有不知道..?
Fetch functions:获取功能:

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

Validate function:验证 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 }

Please help.Thanks in advance!请帮助。在此先感谢!

Something like this should work:像这样的东西应该工作:

Server code:服务器代码:

Simplify validate function.简化验证 function。

export const isValid = (email) => {
  if (email === 'forbidden@gmail.com') {
    return false
  }

  return true
}

Then on your route, something like this, assuming expressjs behind.然后在你的路线上,像这样,假设 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')
})

In your frontend you can just post to /subscribe with the email payload在您的前端,您可以使用 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())
};

And in your sendData you can catch the error, like you're doing在您的 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!')
    });
}

Sidenote: In most cases prototyping should be avoided in javascript.旁注:在大多数情况下,应避免在 javascript 中进行原型设计。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM