Accessing parameters from nodeJS/ExpressJS sent from html form by POST Method - node.js

I would like to know the command to access parameters sent through post method from HTML Forms
I have tried all these but they print undefined or sends back an error ...
EDIT 1: Forgot to mention, I have also added this server.use(express.bodyParser());
EDIT 2:
var express = require('express'),
server = express(),
client = require('mysql').createConnection({ host:'localhost', user:'root', password:'password' });
using dbCRUD for rest services in MySQL
var dbcrud = require('dbcrud').init(client, 'contacts', model);
then I do a
server.use(express.bodyParser());
the post functionality is carried out here..
server.post('/families',function(req,res){
console.log(req.id);
console.log("1: " + req.param.id);
console.log("2: " + req.params.id);
console.log("3: " + req.param("id"));
console.log("4: " + req.params('id'));
console.log("5: " + req.params[0]);
console.log("6: " + req.body.name);
console.log("7: " + req.body.notes);
console.log("8: " + req.body.id);
//console.log("5: " + req.params[0]);
res.send('Hello POST : families');
});
I add the routes here...
dbcrud.addRoutes(server);
In HTML Form i have specified the id and name attributes for the input tag ...
<form method="post" action="http://10.180.218.72:3000/families">
id : <input type="number" id="id" name="id"></input>
name : <input type="text" id="name" name="name"></input>
notes : <input type="text" id="notes" name="notes"></input>
<input type="submit" value = "submit" ></input>
</form>

Try app.use(express.bodyParser()); in your code. bodyParser is a express middleware for parsing body of post request.

Related

what is use of router and model in loopback

hello guys i m new to loopback so can anyone help me with this basic. i had created a some code but don't know how this flow (from route to model)
here is route.js code for login
var path = require('path');
module.exports = function(app) {
app.get('/', function(req, res) {
res.render('login');
});
app.post('/login', function(req, res) {
//from here i should go to login model
});
};
here is my login.ejs
<form action="/login" method="post">
<input type="text" name="username" placeholder="username">
<input type="password" name="password" placeholder="password">
<input type="submit" name="" value="Submit">
</form>
now my question is that how i can use login model from route.js (url is like "login") i know i can use this type as describe below in route.js but i want that first it go to router and from then i go to login model more description eg it go through "/login" route from there it go to login model where i want to add insert login after that if it response success then it go to "/home" else it go to "/"
"var User = app.models.user;"
i what something like this in user.js (model)
module.exports = function(User) {
//here i want to accept login form method and insert it into dataabase
};
or this is not possible or it is incorrect way i don't know much so please help
what is different between if i use business login in router and model i m new so please help.
First go to the loopBack documentation and read it carefully how to create models and its control flow , surely you will get clear picture
https://loopback.io/doc/en/lb2/Project-layout-reference.html

how to send the selected drop down element from client to server using node js - express

I am new to node js and i am stuck to send the selected drop down element (like java,angular see below ex ) from client to server using node js - express. When i try to print it in console. system displays an error message "undefined " for drop down elements. Please help me on this. Thanks in advance.
EJS code
<form method="POST" action="/viewreg.html">
<select name="Courses" form="Courses">
<option value="Java">Java</option>
<option value="Angular">Angular</option>
<option value="Automation">Automation</option>
</select>
<input type='submit'name ='register' onclick="form.action='viewreg.html'"
</form>`
Server side -
const http = require('http');
const express = require('express');
const bodyparser=require('body-parser');
const path=require('path');
const hostname = 'x.x.x.x'
const port = 80;
const app = express();
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({extended:true}));
app.use(express.static(path.join(__dirname,'public')));
app.set('view engine','ejs');
app.set('views',path.join(__dirname,'views'));
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({extended:true}));
const dir=path.join(__dirname,'public');
app.set('view engine','ejs');
app.set('views',path.join(__dirname,'views'));
app.post('/viewreg.html',function(req,res) {
const newuser= {
emp_name:req.body.emp_name,
emp_id:req.body.emp_id,
phone_no:req.body.phone_no,
Team:req.body.selectpicker,
courses:req.body.Courses,
}
console.log(newuser);
});
You need to revisit the below issues which exist in your code.
Change your action url from action="/viewreg.html"> to
action="/viewreg">
There is no need to have onclick="form.action='viewreg.html'" in
your submit button.
You don't have an ID attribute attached to your <select> tag
where as you have a form attribute incorrectly over there.
You need to re-write your ejs tempalte as,
<form method="POST" action="/viewreg">
<select name="Courses" id="Courses">
<option value="Java">Java</option>
<option value="Angular">Angular</option>
<option value="Automation">Automation</option>
</select>
<input type='submit'name ='register'>
</form>
Also try changing your console.log(newuser); as,
console.log(req.body.Courses);
which will resolve your issue.
Hope this helps!

Extracting uploaded csv data with multer

I am porting a rails app over to use the MEEN stack (Mongo, Express, Ember, Node)
I have a function that takes an uploaded csv and extracts the data from it and uses the data to then form SQL queries to a database. For some reason I am having issues with accessing the uploaded csv data with multer.
My Router file
var quotes = require('../api/quote');
var cors = require('cors');
var sku = require('../api/tools/sku');
var multer = require('multer');
var upload = multer({ dest: 'uploads/' });
var util = require("util");
var fs = require("fs");
var corsOptions = {
origin: 'http://localhost:4200'
}
module.exports = function(router){
router.route('/quotes').post(cors(corsOptions),function(req,res){
console.log(req.body);
quotes.addQuote(req,res);
}).get(cors(corsOptions),function(req,res){
quotes.getAllQuotes(req,res);
});
router.route('*').get(cors(corsOptions), function(req,res){
res.sendFile('public/index.html',{root:'./'});
});
router.post('/tools/sku/reactivate',upload.single('csvdata'),function(req,res){
console.log(req.files);
console.log('handing request over to sku.reactivate');
sku.reactivate(req,res);
});
};
My handlebars file for the tools/sku/reactivate template
<div class="col-md-8 col-md-offset-2 text-center">
<h2 class="toolTitle">Reactivate SKUs</h2>
<p class="lead">CSV Should Contain 1 Column (SKU) Only</p>
{{file-upload enctype="multipart/form-data" type="file" url="/tools/sku/reactivate" class="center-block" accept="text/csv" name="csvdata"}}
</div>
i am getting Error: Unexpected field when I attempt to post the file upload to the /tools/sku/reactivate post route. I don't understand whats wrong with my code.
The issue was using the file-upload ember addon. As soon as I removed the handlebars component and just hardcoded a form as seen below, the file upload's successfully.
<div class="col-md-8 col-md-offset-2 text-center">
<h2 class="toolTitle">Reactivate SKUs</h2>
<p class="lead">CSV Should Contain 1 Column (SKU) Only</p>
<form action="/tools/sku/reactivate" method="POST" enctype="multipart/form-data">
<input class="center-block" type="file" name="csvdata">
<button type="submit" class="btn btn-md btn-danger">Submit</button>
</form>
</div>

What am i missing for the file upload using multipart form data ?

Hi for whatever reason i cannot use packages e.g. multer to upload file to node server. So i found example online, if just upload file in the form, it works fine.
Now i want to send another field "password" together with the file during submit, just cannot make it a work.
I do know there're plenty modules out there, for now just want to this example to work.
<form style="height: 100%;padding-bottom:63px;">
<p>
<input type="file" class="FirmwareFile"
name="myUpload" file-model="upload.newFwFile">
</p>
<p>
<input type="password" name="password" id="password"
placeholder="Password"
ng-model="upload.controllerPassword"
class="formInput">
</p>
</form>
httpSvc.uploadToUrl(myFile, myPd, myServerIPAddress, myRoute) {...}
factory.uploadToUrl = function (fwFile, pd, myServerIp, myRoute) {
var fd = new FormData();
//fd.append('passwd', pd); // cannot pass password to server side ?
fd.append('file', fwFile); // only this works
var deferred = $q.defer();
var completeUrl = ......
$http.post(completeUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).success(function (data) {
deferred.resolve(data);
}).error(function () {
deferred.reject();
});
return deferred.promise;
}
in server side, where to extract the password info please ?
var UploadImage = function(req, res, callback){
var destFile = fs.createWriteStream(uploadDest + "mytest");
var fileSize = req.headers['content-length'];
req.pipe(destFile); //why not sth. like req.body.file.pipe() ?
...
};
Your form does not have
<form enctype="multipart/form-data" action="..." method="...">
...
</form>
You will be better off using node-formidable. The example works straight out of the box. You might also want to look into angularJS specific form upload directives that have been made. No sense in reinventing the wheel.
Cheers

How to upload a file to Parse.com using simple HTML form?

I want to upload a simple image file along with text value to a Parse.com project at www.willubmy.com/create. But either I am not getting the correct enctype or Parse's node requires some changes. Can you please help resolve this issue? I am getting the POST variables normally but am not able to get anything when I send a file along
Simplified HTML
<form>
Question:<br>
<input type="text" name="questionString">
<br>
username:<br>
<input type="text" name="username">
<input type="file" name="file">
</form>
My Cloud Code
app.post('/create', function(req, res) {
var username = req.body.username;
var questionString = req.body.questionString;
var positiveAnswer = req.body.positiveAnswer;
var negativeAnswer = req.body.negativeAnswer;
var email = req.body.email;
console.log(username + questionString + positiveAnswer + negativeAnswer + email + JSON.stringify(req.body));
console.log("req files : " + req.files);
This documentation can help you:
https://www.parse.com/questions/uploading-files-to-parse-using-javascript-and-the-rest-api

Resources