Home>
The problem i am experiencing, the shape i am aiming for

In Node.js, the following two submit buttons are placed in one form, and I want to perform different actions when clicked.
So I tried to do it with onClick, but it doesn't work.

<form method = "post">
<input type = "submit" name = "search" value = "search" onClick = "btn1 ()">
<input type = "submit" name = "save" value = "save" onClick = "btn2 ()">
</form>
router.post ('/', (req, res, next) =>{
    function btn1 () {
        // Search process
        new MyData (). where ("a", "=", req.body.a) .fetch (). then ((collection) =>{
            var data = {
                form: req.body,
                mydata: collection
            };
            res.render ("index", data);
        })
    }
    function btn2 () {
// Save processing
}
});


However, even if I push the button, it keeps reading and does not move.

In PHP

if (isset ($_ POST ['search'])) {
// Search process
} else if (isset ($_ POST ['save'])) {
// Save processing
}


I think that the button can be identified by doing like this, but what should I do with Node.js?
Professor

  • Answer # 1

    From the router argument, NodeJS + Express, right?

    NodeJS

    Client (browser) to serverrequest

    Server-to-browserresponse
    Must be considered in full.

    Since it is a JavaScript browser processing to send with the button on the browser, respond to the GET request,
    When a POST request is made by a browser button operation (value corresponding to$_ POST ['search']or$_ POST ['save']in PHP) req. Stored in body.
    Separating with if is the same as PHP.

    router.post ('/', (req, res, next) =>{
      / * JavaScript for browser: Don't write here and respond correctly
      function btn1 () {
      }
      function btn2 () {
    }
      * /
      // The body analysis middleware at the time of POST request stores it in req.body
      console.log (req.body);// Check with middleware
      // If req.body.save, req.body.search ...
      if (req.body.save) {
        // Check save, save processing&response
      }
      else if (req.body.search) {
        // Check search, search processing&response
      }
    });

    Since it has been a long time since I switched to Koa, I'll show you ExpressV4: Request.body