简体   繁体   中英

Calling a function based on locals passed in Javascript - ExpressJS

Consider the following scenario.

I am passing errors from nodeJS after validating a form. The page then reloads and the errors are loaded onto the refreshed page. However, the form itself is actually located inside a modal. How can I open that modal when errors are passed in a function like res.render() on server side?

How do I trigger a function located on a client-side js file based on a locals variable from the server side?

Server Side Code is something like this :

router.post('/create', [
    check('company_name').not().isEmpty().withMessage('Company Name must not be empty'),
    check('contact_name').not().isEmpty().withMessage('Contact Name must not be empty'),
], (req, res, next) => {
    const errors = validationResult(req);

    if(!errors.isEmpty()){
        req.flash( 'errors', errors.mapped() );
        res.redirect('/client');
    } else {
        console.log('No errors found');
        var newClient = new client({
            company_name : req.body.company_name ,
            contact_name : req.body.contact_name ,
        });

        newClient.save(function(err){
            if (err) throw err;
        });

        console.log("Client Created!");
        req.flash('success_msg', 'You have created a new client!');
        res.redirect('/client');
   }
});

you can pass that variable as in url and then on your init function or so like : http://yourdomain.com/sompage.whatever?error=yes; On the client at the beginning check for that variable in url if verifies some checks then show the modal. You can use URL Query String and or URL Parameters for an example of knowing the differences : What is the difference between URL parameters and query strings?

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