Search code examples
javascriptnode.jsexpressbody-parser

How to handle input from switch in Node js


I'm using express and I am completely lost how can I get input from switch, I want to create something like real time application when I toggle the switch, something happens on the server side. I use bootstrap so here is piece of html that I`m using

    <form action="/apps" method="post">    
        <div class="form-check form-switch">
            <input class="form-check-input" type="checkbox" role="switch" id="Switch">
            <label class="form-check-label" for="flexSwitchCheckDefault">Default switch checkbox input</label>
        </div>
    </form>

Here is my code in Node js

app.post('/apps', bodyParser.urlencoded({ extended: true }), (req, res, next) => {
    console.log("Shit is working")
});

But nothing seems to happen when I toggle the switch. I appreciate any response or help because I`m new at Node js.


Solution

    1. Your <input> needs value and name attributes:

    2. You need to post the form which will send the form data to the server. For that you'll need a <button>.

    Your form will look like:

    <form action="/apps" method="post">    
       <div class="form-check form-switch">
          <input value="batman" name="superhero" class="form-check-input" type="checkbox" role="switch" id="Switch">
          <label class="form-check-label" for="flexSwitchCheckDefault">Default switch checkbox input</label>
       </div>
       <button type="submit">Submit</button>
    </form>
    
    1. You need to capture the form data using the name attribute you set on the <input>. This will be parsed and added to the req.body object by Express and the bodyParser middleware like so:
    import express from 'express';
    const app = express();
    app.use(express.urlencoded({ extended: true} )); //< Same a bodyParser.urlencoded
    app.use(express.json()); //< Same a bodyParser.json
    const port = 3000;
    
    app.listen(port, () => {
        console.log(`Connected on port: ${port}`);
    });
    
    app.post('/apps', (req, res) => {
       const hero = req.body.superhero //< Will be 'batman'
       console.log("hero=", hero);
       console.log("mydata=", req.body);
       res.send({ superhero: hero });
    });
    
    1. Once you have these fundamentals nailed you can move on to sending your form using JavaScript with fetch/axios by binding an event listener to the checkbox so that a request is sent "behind-the-scenes" every time the checkbox is switched on or off.