簡體   English   中英

獲取JS時如何拋出服務器錯誤

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM