POST data from multiple forms in single request using Node.js - node.js

I'm trying to send a POST request to an API from multiple forms at once. Essentially I have a site where users will input data to multiple locations before clicking a button to run a calculation. Clicking the button will ideally send a POST request to the API containing all the information the user has input from various places.
Within the body of index.html I've tried the following, effectively trying to get both forms to POST to the same address, but only including a submit button with one.
<form action="/" method="post" name="myForm">
<div>
Here is some text at the top of the form...
</div>
<input type="text" name="num1" class="inp1" placeholder="First Number">
<input type="text" name="num2" class="inp2" placeholder="Second Number">
<button type="submit" name="submit">
calculator
</button>
</form>
<form action="/" method="post" name="myForm">
<div>
Here is a 2nd form
</div>
<input type="text" name="num1" class="inp1" placeholder="Third Number">
<input type="text" name="num2" class="inp2" placeholder="Fourth Number">
</form>
My Node.js code to spin up a server and look at the POST request:
const fs = require("fs");
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(
bodyParser.urlencoded({
extended: true,
})
);
const tempResult = fs.readFileSync(
`${__dirname}/templates/overview.html`,
"utf-8"
);
app.get("/", (req, res) => {
res.send(tempResult);
});
app.post("/", (req, res) => {
console.log(req.body);
res.send(tempResult);
});
const port = 3000;
app.listen(port, () => {
console.log(`App running on port ${port}...`);
});
In the console this simply returns:
{
num1: val1,
num2: val2,
submit: ''
}
Where val1 and val2 are the inputs to index.html for the first form only. What am I missing here? How can I get the values from both forms in one call?

As alluded to by #Ipizzinidev the solution here lies in putting the form right at the top of the body.
<body>
<form action="/" method="POST">
<div>
Here is some text at the top of the form...
</div>
<input type="text" name="num1" class="inp1" placeholder="First Number">
<input type="text" name="num2" class="inp2" placeholder="Second Number">
<input type="text" name="num3" class="inp3" placeholder="Third Number">
<input type="text" name="num4" class="inp4" placeholder="Fourth Number">
<button type="submit" name="submit">
calculator
</button>
</form>
</body>
Inside this form you can do the usual HTML stuff and then after hitting submit it will return the following:
{
num1: val1,
num2: val2,
num3: val3,
num4: val4,
submit: ''
}
It always seems so simple in hindsight!

Related

Post request from ejs view is not working

I'm trying to register a user to my database but I can't even make my post request work. The get part router is working but it seems post is not working.
In the app I declared routers like this(server.js file):
const userRoutes = require("./routes/user.js")
app.use('/user',userRoutes)
In the routes/user.js file:
//User register
const userController = require('../controllers/user_controller')
router.get("/register",userController.register_page)
router.post("/register",userController.register_post)
And this is the controller part (controllers/user_controller.js):
//Register get
exports.register_page = (req,res)=>{
return res.render('user/register',{layout:false})
}
//Register post
exports.register_post = async (req,res)=>{
//bla bla
}
I can see the pages but when I submit in the ejs page nothing happens. This is the view page(views/user/register.ejs):
<form id="register" method="post" action="/user/register">
<label><b>Email
</b>
</label>
<input type="text" name="email" id="email" placeholder="Email">
<br><br>
<label><b>Password
</b>
</label>
<input type="Password" name="password" id="password" placeholder="Password">
<br><br>
<label><b>Confirm Password
</b>
</label>
<input type="Password" name="confirm" id="confirm" placeholder="Password Repeat">
<br><br>
<input type="button" name="submit" id="submit" value="Register">
</form>
Your form does not send the post request, because the submit button does not have the type of submit. Change from type="button" to type="submit".

Handling post request for 2 forms in one page using express

I have two forms, newsletter signup form and contact form in one page. I want to make post request for both using node and express. How can I do it?
Here's the html code for the forums:
<!-- Newsletter signup Section -->
<section class="newsletter-section">
<form action="/" method="POST">
<span class="newsletter-heading u-text-align-centre u-margin-bottom-medium">
Subscribe to our monthly newsletter!
</span>
<div class="row u-text-align-centre">
<input type="text" name="email-address" class="newsletter-input">
Sign Me Up!
</div>
</form>
</section>
<!--contact section-->
<section class="contact-section">
<div class="contact-container">
<h2>Contact Us</h2>
<div class="container">
<div class="customer-info">
<form class="contact-form" action="/" method="POST">
<div class="name">
<div class="first-name">
<label for="first-name">First Name</label>
<input type="text" id="name" placeholder="First Name" />
</div>
<div class="last-name">
<label for="last-name">Last Name</label>
<input type="text" id="name" placeholder="Last Name" />
</div>
</div>
<div class="contact-info">
<div class="email">
<label for="email">Email</label>
<input type="email" id="email" placeholder="email" />
</div>
<div class="tel">
<label for="tel">Tel</label>
<input type="tel" id="tel" placeholder="tel" />
</div>
</div>
<div class="reason">
<label for="reason">How may we help you?</label>
<select name="reason" id="reason">
<option value="">Select an option</option>
<option value="Customer-service">Customer Service</option>
<option value="book-event">Book for an event</option>
<option value="place-order">Place Order</option>
<option value="inquiries">Inqiries</option>
<option value="####">Other</option>
</select>
</div>
<div class="short-message">
<textarea id="message" rows="10" placeholder="Type a short message here"></textarea>
</div>
<div class="save-info">
<span>Save my info for next time</span>
<input type="checkbox" class="final-input" />
</div>
<div class="submit">
<button name="submit" class="btn-round">Send</button>
</div>
</form>
</div>
</div>
</div>
</section>
And this is the code for the node.js:
const express = require('express');
const bodyParser = require('body-parser');
const ejs = require('ejs');
const _ = require('lodash');
const app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));
app.get('/', function (req, res) {
res.render('home', { homeContent: homeStartingContent, posts: posts });
});
That was all of the code. Now I want to add the post request for each of the forms sepeartely.
You need to set the action parameter of each form element to a different URL (eg. /contact and /subscribe or whatever you prefer), and then create a route in your API to handle requests to each of these.
Currently, with the action set to "/", you're sending the output of both forms to the same endpoint in your backend.
<form action="/subscribe" method="POST">...</form>
<form action="/contact" method="POST">...</form>
app.get('/', function (req, res) {
// Display the forms
res.render('home', { homeContent: homeStartingContent, posts: posts });
});
app.post('/subscribe', function (req, res) {
// Deal with the contents of the submitted subscription form
});
app.post('/contact', function (req, res) {
// Deal with the contents of the submitted contact form
});

error in post request to a route in index.js file inside firebase cloud functions

i have craeted a from in index.html and using it , i am sending a POST request to an express route written inside firebase cloud functions.
when i deploy the app and login using that form i am redirected to the route but the page shows " internal server error"
also, if i dont deploy and just serve the functions and go to /home route, it gets rendered.
please help .
thankyou
my index.html login form :
<!--LOGIN -->
<div id="login" class="modal">
<form class="modal-content" method="POST" action="https://samsungmap-17515.web.app/home">
<div class="container">
<h1>Login</h1>
<p>Please fill in this form to Login.</p>
<hr>
<label for="email"><b>Email</b></label>
<input type="text" placeholder="Enter Email" id="email2" required>
<label for="roll no"><b>Roll NO.</b></label>
<input type="text" placeholder="Enter Roll Number" id="roll2" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" id="psw2" required>
<div class="clearfix">
<button type="button" onclick="document.getElementById('signup').style.display='none'" class="cancelbtn">Cancel</button>
<button type="submit" class="signup">Sign Up</button>
</div>
</div>
</form>
</div>
my index.js file :
const functions = require('firebase-functions');
const express = require('express');
const firebase = require('firebase-admin');
const firebaseApp = firebase.initializeApp(
functions.config().firebase
);
const db = firebaseApp.firestore();
const app = express();
app.set('view engine','ejs');
//-------------------------------------------------------------------//
app.get("/home",(req,res)=>{
res.render("teacher",{bio:"Chahat"});
});
exports.app = functions.https.onRequest(app);

How to make a function of arrays in node js, handlebars

I was new to node.js and trying to render a list of fruits using hbs or handlebars in the client that came from the server
I wonder how to make a functions or event in every fruits
This is how i render the fruits
app.js
app.post('/getList', function(request, response) {
if (request.session.loggedin) {
//here i am sending the arrays to the client in the homepage
response.render('home',{fruits:fruits()});
} else {
response.send('Please login to view this page!');
}
This is my home.bhs
<form action="getList" method="POST">
<input type="text" name="username" placeholder="Username" >
<input type="password" name="password" placeholder="Password" >
<input type="submit" value="Insert">
<ul>{{#each fruits}}</ul>
<li>{{this}}</li>//Here are the list of frutis and i want to make them clickable
{{/each}}
</form>
});
This is my arrays
let fruits=()=>{
let list = ["apple","asdas","bbb","ccc","dddd"];
return list;
};

Why is it giving me a "you sent the name undefined" error when I send my HTML form in electron to my express server?

I've been using electron to create a desktop app and I've been having trouble sending the input form data to my express server as it gives me the "you sent the name undefined" error. I was wondering if anyone can point me in the right direction. Thanks! Here is my code.
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/myaction', function(req, res) {
res.send('You sent the name "' + req.query.name + '".');
});
app.listen(8080, function() {
console.log('Server running at http://127.0.0.1:8080/');
});
<form action="http://127.0.0.1:8080/myaction" method="post">
<input type="email" name="email" id="fremail" placeholder="your#email.com" required/>
<br>
<input type="submit" name="Submit" value="Continue" />
<br>
</form>
<br>
<br>
<br>
<form action="http://127.0.0.1:8080/myaction" method="post">
<input class="inputNum" type="number" min="1000" max="9999" name="num1" id="num1" placeholder = "XXXX" required/>
-
<input class="inputNum" type="number" min="1000" max="9999" name="num2" id="num2" placeholder = "XXXX" required/>
-
<input class="inputNum" type="number" min="1000" max="9999" name="num3" id="num3" placeholder = "XXXX" required/>
-
<input class="inputNum" type="number" min="1000" max="9999" name="num4" id="num4" placeholder = "XXXX" required/>
<br />
<input type="submit" name="Submit" value="Continue" />
</form>

Resources