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.
Your <input>
needs value
and name
attributes:
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>
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 });
});