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

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!

Related

Node JS Express routing with method-override. Can someone explain why _method=DELETE works with my router using route.post, but not route.delete?

app.js
const methodOverride = require ('method-override');
const app = express();
// Method Override Midware
app.use(methodOverride('_method'));
Router
const express = require('express');
const router = express.Router();
// Pass all routes through adminController
const adminController = require('../controllers/adminController');
router.route('/posts/delete/:id')
.post(adminController.deletePost);
//.delete(adminController.deletePost);
HTML
<form action="/admin/posts/delete/{{id}}?_method=DELETE" method="post">
<button class="btn btn-sm btn-danger" type="submit">Delete Post</button>
</form>
I spent a good while trying to figure this out and it turns out the solution for a successful deletion was to remove route.delete and replace it with route.post in my router. But I don't understand why this works and .delete doesn't. As far as I know, HTML forms can only GET and POST, but I assumed method-override would circumnavigate this and let me type .delete directly. So now I'm confused as to whether it's the import for override that's not working properly, or if it's working fine and I still need to .post every time regardless and just change the endpoint's method in my HTML?
Thank you

rendered handlebars partials with node.js printing unnecessary spaces

I'm new at node.js and i'm using handlebars(hbs), i have created a views and some partials, and everything goes well, but the problem is the rendered partials have unnecessary spaces which makes the page looks bad, here is my code :
handlebars view
{{>header}}
<h1>{{ title }}</h1>
{{>footer}}
handlebars partial (footer)
<footer>
Created By Hassan Ali
</footer>
and here is my app.js
const path = require("path")
const express = require("express")
const hbs = require("hbs")
const app = express()
// Folders Pathes
var publicFolder = path.join(__dirname, "../public")
var viewsFolder = path.join(__dirname, "../templates/pages")
var partialsFolder = path.join(__dirname, "../templates/components")
// Setting The View Engine
app.set('view engine', 'hbs')
// Setting The Views Directory
app.set('views', viewsFolder)
// Setting The Views Components
hbs.registerPartials(partialsFolder)
// Setting The Static Folder
app.use(express.static(publicFolder))
app.get("/notes", (req, res) => {
res.render("notes", {
title: "Notes App"
})
})
and when it's rendered i get some unnecessary spaces in the html before every partial with this &-#65279; entity (without - that after &)

<header>
Header Tag
</header>
<h1>Title of The Page</h1>

<footer>
Created By Hassan Ali
</footer>
any help will be appreciated.
EDIT: The problem is solved Thanks

Cannot POST /addfriend error using Express

I am trying to create a simple form handler using express. Here is a similar question but I can't related it with my problem. I have written all of my file Here anyone can check it by using all of my file. For better understanding I copy my code here:
app.js code:
const express = require('express');
const app = express();
//routes
app.get('/',function(req,res){
res.send('This is root dir');
});
app.get('/friends',function(req,res){
var friends=['sakib','emon','rayhan'];
res.render('friends.ejs',{friends:friends});
});
app.get('/addfriend',function(req,res){
res.send('ADD friend page launch!!!!!');
});
app.listen(3000,function(){
console.log("server has started on port 3000!!!");
});
ejs(friends.ejs) code:
<h1>Here is list of your Friend:</h1>
<%friends.forEach(function(friend){%>
<li><%=friend%></li>
<%});%>
<form action="/addfriend" method="POST">
<input type="text" name="friend" placeholder="name">
<button>
Submit
</button>
</form>
When I type any name in the input box and clicked Submit it didn't post to /addfriend. I didn't understand where is my problem. Please goto input box(link) after started the server.
For better understand what's my actual problem is then please use goorm IDE(shared file) where I uploaded everything.
You are using get request instead of post for addfriend.
app.post('/addfriend',function(req,res){
console.log("I'm called wohoo!");
res.send('ADD friend page launch!!!!!');
});

(Self Q&A) HOW TO SETUP AND USE the MULTER MIDDLEWARE) for single file upload ( Expressjs/Nodejs )

Just wanted to post an answer to a beginner level question on HOW TO SETUP AND USE the MULTER MIDDLEWARE in Expressjs/Nodejs
Hope this saves your time
There should be two files:
1.Jade file(which shall contain the form lets assume index.jade)
2.JS file(which is located in the routes folder, and which directs to the index.jade file in the views folder)
SETUP index.jade file
//not a jade file so convert it to jade
//enctype is set to multipart/form-data --- multer requirement
<form method="post" role="form" enctype="multipart/form-data">
<div class="form-group">
<label for="upload">Email address:</label>
//name attribute to access in index.js route file
<input type="file" class="form-control" name="upload" id="upload">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
//very important
(a)In the Jade file the form must contain the attribute of enctype = "multipart/form-data"
(b)Input should have a name attribute which gets accessed in the index.js file
SETUP JS ROUTE FILE(index.js) not in app.js
var express = require('express')
var multer = require('multer')
var upload = multer({ dest: 'uploads/' }) //set dest to where you want to upload the file
var app = express()
// SINGLE FILE UPLOAD
app.post('/', upload.single('upload'), function (req, res, next) {
//since we are performing a single file upload req.file will be used and not req.files
// req.file would attach the file with upload fieldname ~ upload is the name attribute given in the form
//now use req.file to access the file
//for example
console.log(req.file); // this would display the file attributes in the log
})

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>

Resources