简体   繁体   中英

Validate input in Nodejs/Express back-end and send result to React front-end

I want to check if a domain (eg. google.com ) that a user enters in my React front-end is valid.
I'm sending the domain to my Nodejs/Express back-end and using the Node function dns.lookup to check if the domain is valid as follows:

app.post('/new-cert', function (req, res) {
    var lookup = dns.lookup(req.body.deletedCert, function (err, addresses, family) {
        console.log(addresses); //eg.74.125.224.72 or undefined
    });

    // Only run this bit if `addresses` above is NOT `undefined`
    fs.appendFile('certs-list', '\n' + req.body.domainInput, function (err) {
        res.send('POST request: ');
        exec('sh cert-check-script-insert.sh');
        if (err) throw err;
    });
});

If addresses is undefined then I want to tell my React front-end that the domain entered is invalid and then it can print a relevant message to the user.
Else I want to run the rest of the function from fs.appendFile onwards to go ahead and insert the domain.

Sorry I'm new to React/Node and was unable to find a post which could help me, any help is appreciated!

Example:

Express:

if (addresses) {
    res.send(addresses)
} else {
    res.status(404).send({message: "Address not found with " + req.body.deletedCert})
}

React:

const response = await fetch('/new-cert', config)
if (response.ok) {
    const json = await response.json()
    this.setState({adresses: json})
} else {
    alert('Could not find the domain.')
    return
}

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