How to pass data from html client to NodeJS server? - html

I would like to send some data from client to NodeJS server using POST method.
Below is my part of html code.
<form action="http://localhost:8080/data/name/:name/ssn/:ssn" method="post" id="signup">
<h1>Personal info post example</h1>
<div class="field">
<label for="name">Name:</label>
<input type="text" id="name" placeholder="Enter your fullname" />
<small></small>
</div>
<div class="field">
<label for="ssn">SSN:</label>
<input type="text" id="ssn" placeholder="Enter your SSN" />
<small></small>
</div>
<button type="submit">Submit</button><br><br>
</form>
Below is my part of server.js.
I tried to print out everything that I can think of what I can.
I wrote down the results as comments as well.
This is the result when I enter 'a' for the name and 'b' for the ssn and submit it.
app.post('/data/name/:name/ssn/:ssn', function(req, res) {
console.log('req.query: ', req.query); // {}
console.log('req.query.name: ',req.query.name); // undefined
console.log('req.query.ssn: ',req.query.ssn); // undefined
console.log('req.params: ',req.params); // { name: ':name', ssn: ':ssn' }
console.log('req.params.name: ',req.params.name); // :name
console.log('req.params.ssn: ',req.params.ssn); // :ssn
});
When I type 'a' and 'b' into search boxes and hit the submit button, the web browser starting to load but never ends and my VSC shows the result.
Can anyone help me what I need to fix?

looks like you're mixing req.params and req.query, while you actually need req.body
try this:
add this to server.js (you need to install body-parser):
const bodyParser = require('body-parser');
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
// parse application/json
app.use(bodyParser.json());
app.post('/data', function(req, res) {
console.log('req.body: ', req.body);
const {name, ssn} = req.body;
console.log('name: ', name);
console.log('ssn: ', ssn);
res.json(req.body);
});
and change HTML form (add name attribute, that's your data):
<form action="http://localhost:8080/data" method="post" id="signup">
<h1>Personal info post example</h1>
<div class="field">
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="Enter your fullname" />
<small></small>
</div>
<div class="field">
<label for="ssn">SSN:</label>
<input type="text" id="ssn" name="ssn" placeholder="Enter your SSN" />
<small></small>
</div>
<button type="submit">Submit</button><br><br>
</form>

your code is good. But you are facing this problem because the server is not sending any data after submit.
First, there should be something to handle GET:
var express = require('express');
var app = express();
app.get('/', (req, res)=>{
res.sendFile('index.html');
console.log('Someone saw your website!');
})
app.listen(80);
Secondly, return something after submit:
app.post('/data/name/:name/ssn/:ssn', function(req, res) {
console.log('req.query: ', req.query); // {}
console.log('req.query.name: ',req.query.name); // undefined
console.log('req.query.ssn: ',req.query.ssn); // undefined
console.log('req.params: ',req.params); // { name: ':name', ssn: ':ssn' }
console.log('req.params.name: ',req.params.name); // :name
console.log('req.params.ssn: ',req.params.ssn); // :ssn
res.end('Thankyou, \n Your Name:'+req.params.name+'\n Your Ssn:'+req.params.ssn);
});

Related

Trying to send a login form input to database using html and nodejs

I am trying to create a login page using html and node.js. I have been able to send stuff to the database using only node.js and postman but now I am trying to get it working with my html page. When trying to send stuff, I get sent back to index.html and a scripts.js error. The scripts.js error comes from the index.html page but it only happens when I get redirected. That error is not my problem though because I cant even get my db to update which is the biggest part I am trying to solve.
app.js
app.use('/public', express.static(path.join(__dirname, 'static')));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'static', 'index.html'));
});
app.use(bodyParser.json());
const { urlencoded } = require('body-parser');
app.use(express.urlencoded({ extended: true }))
const authRoute = require('./routes/auth');
app.use('/api/user', authRoute);
app.use('/api/posts', postRoute);
I am using a routes folder where I contain the auth.js. auth.js also contains the methods I use to login in and registering a account
auth.js
const User = require('../models/User');
const { registerValidation, loginValidation } = require('../validation');
router.post('/register', async (req, res) => {...}
router.post('/login', async (req, res) => {...}
register.html
<form action="/" method="/api/user/register">
<input type="name" placeholder="Name" name="name" id="name" required>
<input type="text" placeholder="Email" name="email" id="email" required>
<input type="password" placeholder="Password" name="passwrd" id="password" required>
<!-- <input type="password2" placeholder="Repeat Password" name="psw-repeat" id="psw-repeat" required> -->
<!--<button type="submit" class="registerbtn">Register</button>-->
<input type="submit" value="Continue">
</form>
</div>
</div>
Using postman when I need to register a account I do
http://localhost:3000/api/user/register
{
"name": "POST MAN",
"email": "RDM#EMAIL.com",
"password": "123456"
}
Similar to login except I do /login and only use email and password. If I can get the register part working than I would be able to get the rest working as well.
Try modifying Form tag’s attributes in html
action=“BE URL or api Path”
method=“POST”
Reference: https://www.w3schools.com/tags/att_form_method.asp

nodejs getting another page

I have a small problem about nodejs and html. There is an error somewhere that I couldn't see. I have been getting this error for 2 days. (cannot get /aP.html)
There is nothing wrong about sql connection, and first and second pages. But when I want to go aP.html from secondpage I keep getting this error.
My nodejs code:
var mysql = require('mysql');
var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
var connection = mysql.createConnection({
......
});
connection.connect((err) => {
if(err){
throw err;}
else console.log("connected");
});
var app = express();
app.use(bodyParser.urlencoded({extended : true})); //forma girilen datanın parse edilebilmesi için
//başka directorylerdeki klasörleri kullanacaksan
app.use('/js', express.static(__dirname + '.....'));
//gidilecek sayfa
app.get('/', function(request, response) {
res.render('/aP.html', {});;
});
console.log("got it");
app.post('/aP.html', function(request, response) {
var p_name = request.body.urun_adi;
var code = request.body.barkod;
var quantity = request.body.stok_sayi;
var price = request.body.satis_fiyati;
var cost = request.body.maliyet;
var supplier = request.body.firma_adi;
// var username = request.body.id;
/* foreign key olan user id burada kullanılacak mı?*/
console.log(p_name);
connection.query( "INSERT INTO `stok` (`urun_adi`, `barkod`, `stok_sayi`, `satis_fiyati`, `maliyet`, `firma_adi`) VALUES ('"+p_name +"','"+ code +"','"+ quantity +"','"+ price +"','"+ cost +"','"+ supplier+"')");
if(err) throw err;
response.send('save succesful');
});
app.listen(3000);
My HTML code(just for trying):
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="/aP.html" method="post" class= "col s12">
<input type="hidden" name="e_id" value="">
<div class="form-group row">
<label for="p_name" class="col-2 col-form-label"> Adı</label>
<div class="col10">
<input type="text" name="p_name" value="" class="form-control">
</div>
</div>
<div class="form-group row">
<label for="code" class="col-2 col-form-label"> Barkod</label>
<div class="col10">
<input type="text" name="code" value="" class="form-control">
</div>
</div>
<div class="form-group row">
<label for="quantity" class="col-2 col-form-label"> Adet</label>
<div class="col10">
<input type="text" name="quantity" value="" class="form-control">
</div>
</div>
<div class="form-group row">
<label for="price" class="col-2 col-form-label"> Fiyat</label>
<div class="col10">
<input type="text" name="price" value="" class="form-control">
</div>
</div>
<div class="form-group row">
<label for="cost" class="col-2 col-form-label"> Maliyet</label>
<div class="col10">
<input type="text" name="cost" value="" class="form-control">
</div>
</div>
<div class="form-group row">
<label for="supplier" class="col-2 col-form-label"> Tedarikçi</label>
<div class="col10">
<input type="text" name="supplier" value="" class="form-control">
<input type="submit" name="submit" value="Save Stock">
</div>
</div>
</form>
</body>
</html>
What view engine are you using? If it is ejs you will have to require it and change some of your code. Look at my example and maybe it will clear things up for you. If this is your question.
first npm install ejs
Index.js or server.js depending on what you name it. (start file)
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(express.static("public"))
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs');
app.set("port", 3001)
app.get('/', function (req, res) {
res.render('index')
});
app.use('*', function (req, res) {
res.status(400);
res.json({
'error': 'Deze URL is niet beschikbaar.'
});
});
app.listen(process.env.PORT || 3001, function() {
console.log('De server luistert op port ' + app.get('port'));
});
module.exports = app;
Then create a views directory in the root of the project. (same level as the index.js) It is important that you name it that.
In the views folder create a file (in your case aP) with .ejs extension. No HTML extension, because you will use the ejs view engine. It will automatically search in de views directory for the ejs files. Put the html code from aP.html into the newly created aP.ejs file.
I hope this is the answer you are looking for if there are any other problems or you want to do it differently, please let me know.
Edit: different way without ejs
Change this line:
app.get('/', function(request, response) {
res.render('/aP.html', {});;
});
Into this:
app.get('/', function(request, response) {
response.sendFile(path.join(__dirname+'/aP.html'));;
});
Make sure the aP.html is on the same level as the index.js file.
Your problem was (I think) that is didn't recognize res because you name it response. Furthermore you should use sendFile and it will work. I hope this helped.

How to send data to HTML page and how to use AJAX for Single Page Application in NodeJS Server using express.js framework?

How can I display the form submitted data in another HTML Page
From 1st page (page1.html)collecting the data from users and after appending this data in the database I want to show the submitted values in another page i.e.(page4.html)
Below is my code
I have tried using res.sendFile or res.send
server.post('/addname', (req, res) => {
const user = {
timestamp: new Date,
FName: req.body.FName,
LName: req.body.LName,
Phone: req.body.Phone,
Email: req.body.email,
Contact: req.body.business,
Business: req.body.contact,
OTP: req.body.otp_field
}
res.sendFile(__dirname + '/page4.html');
//along with file rediraction, how can i send or show the "User" vaules in respactivte filed
});
<body>
<div>
<div align="center">
<form action="/addname" method="GET">
<label>Please enter below details</label><br><br>
<label>First Name *: </label><input id="FName" type="text" name="FName"/><br><br>
<label>Last Name *: </label><input id="LName" type="text" name="LName"/><br><br>
<label>Email Address *: </label><input type="email" name="email"><br><br>
<br><br>
<input type="submit" value="Submit" /></form>
</div>
</div>
</body>
nAs I can see in your code
<body>
<div>
<div align="center">
<form action="/addname" method="GET">
<label>Please enter below details</label><br><br>
<label>First Name *: </label><input id="FName" type="text" name="FName"/><br><br>
<label>Last Name *: </label><input id="LName" type="text" name="LName"/><br><br>
<label>Email Address *: </label><input type="email" name="email"><br><br>
<br><br>
<input type="submit" value="Submit" /></form>
</div>
</div>
</body>
Your form method is "GET", it should be "POST" as your API is "POST".
server.post('/addname', (req, res) => {
<form action="/addname" method="GET">
//Just change to
<form action="/addname" method="POST">
While sending and HTML file you need to send your submitted data too.
res.sendFile(__dirname + '/page4.html');
In order to save your hurdle switch to Single Page Application and use some JavaScript frame work like AngularJs, ReactJs or if not then also stick to single page and use Ajax calls for submit calls.
Else see "ejs" in place of "HTML" and use scriptlet to send and show data over HTML.
To send data to "ejs" via expressJs
res.render('show.ejs', {message});
With Ajax you can do this:
HTML
<body>
<div>
<div align="center">
<form id="form1">
<label>Please enter below details</label><br><br>
<label>First Name *: </label><input id="FName" type="text" name="FName"/><br><br>
<label>Last Name *: </label><input id="LName" type="text" name="LName"/><br><br>
<label>Email Address *: </label><input type="email" name="email"><br><br>
<br><br>
<input type="button" value="Submit" onClick:"submitForm()"/>
</form>
<div id="showValue"></div>
</div>
</div>
</body>
JavaScript
function submitForm() {
$.ajax({
url: '/addName',
type: 'POST',
headers: headers,
data: {
"Fname": $("#FName").val(),
"Lname": $("#LName").val(),
"email": $("#email").val()
},
success: function(result) {
//append result to your html
//Dynamic view
$("#form1").hide();
var html = '<div><span>First Name: ' + result.fName + '</span><span>Last Name: ' + result.lName + '</span></div>';
$("#showValue").html(html);
},
error: function (error) {
alert('error ',error);
}
});
}
Server side code I'm assuming you are using express.js and body-parser
app.post('/addName', (req, res) => {
//Insert into db
var body = req.body;
res.send({
fName: body.FName,
lName: body.LName
});
});

How to handle post request when user hits submit on very basic node.js/html login page

I have created a login page using some HTML/CSS and I want the user to enter a pre-determined password, if the password is correct, they can enter the site, if not, they can't. I have looked up a lot of tutorials/sites etc. but they either use Mongodb to create unique passwords or else use Passport which is not what I'm looking for. I realise having a pre-determined password is not best practice but it suits for the scope of what I'm doing. I plan to change it once I get a basic set up going.
There is a fully functioning site when the user logs in, I just have very little experience with Node.js and not really sure how to handle the post request
This is my the form part of my HTML page (login.ejs)
<form method="post">
<div class="form-group">
<label>Password</label>
<input type="text" class="form-control" name="name" id="name">
</div>
<button type="submit" class="btn btn-warning btn-lg">Login</button>
</form>
And this is my part of my server.js file
var express = require('express');
var config = require('./config');
var bodyParser = require('body-parser');
var mandrill = require('mandrill-api/mandrill');
var app = express();
app.set('view engine', 'ejs');
app.use(express.static('dist'));
app.use(bodyParser.urlencoded({ extended: false }));
//other stuff
app.post('/login', function (req, res) {
//user enters predetermined password
//user hits the submit button
//if password = "login"
//go to home page
//if password != "login"
//go to error page
});
First, you need to specific the action attribute of the form to be the node route you want to send to. Your form will simply change to:
<form method="post" action="/login">
<div class="form-group">
<label>Password</label>
<input type="text" class="form-control" name="name" id="name">
</div>
<button type="submit" class="btn btn-warning btn-lg">Login</button>
</form>
In your node file, since you are using body-parser it is very simple to access the body of the POST request.
app.post('/login', (req, res) => {
var data = req.body.name;
});
Where name is the value of the name attribute on the input tag in your form.
modify client side code as
<form method="post" action="/login">
<div class="form-group">
<label>Password</label>
<input type="text" class="form-control" name="name" id="name">
</div>
<button type="submit" class="btn btn-warning btn-lg">Login</button>
</form>
and modify server side code as:
app.post('/login', function (req, res) {
if (req.body.name == "login")
res.redirect('/home');
if (req.body.name != "login")
res.redirect('/error');
});
app.get('/home', function(req, res) {
// If you are using ejs, you can render ejs
res.sendFile(__dirname + 'path_to_folder_containing_htmls/home.html');
});
app.get('/error', function(req, res) {
// If you are using ejs, you can render ejs
res.sendFile(__dirname + 'path_to_folder_containing_htmls/error.html');
});

Changing form type to multipart/form-data causes req.body to be empty

When I set up my form without specifying an enctype, Firefox automatically sets it to application/x-www-form-urlencoded and req.body contains a nice, JSON representation of all the parameters entered into the form. But when I change the enctype to multipart/form-data req.body is suddenly empty.
This is my form:
<form action="/create" method="post" enctype="multipart/form-data">
<fieldset>
<div>
<label>Category:</label>
</div>
<div>
<select name="category">
<option value="standard">Standard</option>
<option value="custom">Custom</option>
</div>
<div>
<input type="text" name="description">
</div>
<div>
<label>User ID:</label>
</div>
<div>
<input type="text" name="userid">
</div>
<div>
<input type="submit" value="Go">
</div>
</fieldset>
</form>
Doing a console.log(JSON.stringify(req.body, null, 2)); prints out an empty object when enctype is multipart/form-data and when enctype is not specified, it prints out something like:
{
category: "standard",
userid: "foo"
}
Any reason this is happening?
Try use busboy-body-parser to retrieve the request body parameters and the files.
start.js
var bodyParser = require('body-parser');
var busboyBodyParser = require('busboy-body-parser');
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
extended: true
}));
// parse application/json
app.use(bodyParser.json());
//parse multipart/form-data
app.use(busboyBodyParser());
controllers/someController.js
someAction: function(req,res){
if(req.method == "POST"){
res.end(JSON.stringify(req.body)+JSON.stringify(req.files));
}
}
//{"text":"testx"}{"anexo":{"data":{"type":"Buffer","data":.... }}}
//req.body = {"text":"testx"}
//req.files = {"anexo":{"data":{"type":"Buffer","data":.... }}}
views/someController/someAction.html
<form method="post" id="multipart" enctype="multipart/form-data">
<input type="text" id="text1" name="text" value="testx" />
<input type="file" id="anexo" name="anexo" />
<input type="submit" value="Enviar" />
</form>
To create a file uploaded, you need work if the stream, for example:
/* file props
{
"data":{"type":"Buffer","data":.... },
"fieldname":"anexo",
"originalname":"images (1).jpg",
"encoding":"7bit",
"mimetype":"image/jpeg",
"destination":"c:\\live\\sources\\uploads\\",
"filename":"eventclock_images (1)_1443706175833.jpg",
"path":"c:\\live\\sources\\uploads\\eventclock_images(1)_1443706175833.jpg",
"size":9986
}
*/
var fileStream = fs.createWriteStream(file.path);
fileStream.write(file.data);
fileStream.end();
fileStream.on('error', function (err) {
//console.log("error",err);
});
fileStream.on('finish', function (res) {
//console.log("finish",res);
});
Sounds like you're using express.urlencoded() instead of express.multipart().
I think #robertklep is correct, but I disagree with his answer. express.multipart() is deprecated and should not be used.
If you need multipart form processing, I highly recommend Busboy. If you want all the details, see this answer.
npm install multer --save
in main.js
var multer = require('multer');
var upload = multer()
router.route("/quotes").post(upload.array(),function(req, res, next){
name = req.body.name;
email = req.body.email;
}