简体   繁体   中英

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:
When an email is forbidden@gmail.com, the server responds with the 422 status code and payload which contains the information about the error. Use browser developer tools to examine the response for this scenario. Display the error message in the browser using 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..?
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:

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.

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

  return true
}

Then on your route, something like this, assuming expressjs behind.

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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