JoOoBa1000
JoOoBa1000

Reputation: 33

how can i get a response when i post a form to a specific api

i have made an api to get data and save it into mongo db

const userDB = require('./model/user')

app.post ('/signup', function (req, res){
    userDB.find({username: req.body.username}).
    then (result=>{
        if (result.length == 0) {
            bcrypt.hash(req.body.password, 10, function (err, hash){
                if (err) {
                    res.status(404).json ({
                        message : err
                    })
                }else{
                    const user = new userDB ({
                        username: req.body.username,
                        password: hash
                    })
                    user.save().
                    then(result =>{
                        res.status(200).json({
                            message : 'user had been created'
                        })
                    }).
                    catch(err=>{
                        res.status(404).json({
                            message : err
                        })
                    })
                }
            })
        }else{
            res.status(200).json({
                message : 'user already exist'
            })
        }
    }).
    catch(err=>{
        res.status(404).json ({
            message : err
        })
    })
})

and i have made a html register form to post register information to api

how can i receive the api response in client side to make an alert that the operation has succeed or not

Upvotes: 1

Views: 57

Answers (2)

Domenik Irrgang
Domenik Irrgang

Reputation: 21

It all depends on what you use on the client side, if you use vanilla javascript:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    // register success
  }
  if (this.readyState == 4 && this.status == 404) {
    // register failure
  }
};
xhttp.open("POST", "/signup", true);
xhttp.send();

You should consider using appropriate status codes, 404 means page not found, which is clearly not true. In your case 500 (internal server error) seems to be the correct one where you used 404.

Upvotes: 1

Omri Attiya
Omri Attiya

Reputation: 4037

If you want to return a response from your node api to the client who send the request, just use res.send in your api.

res.send(**your data**)

then, in your client, just await for the response or use .then

Upvotes: 0

Related Questions