Parsing html elelments on form POST in NodeJS - javascript

I'm trying to parse select (dropdown) box element on form post.
Request body contains only 'txt1' element. No sign of 'lstSelect' element.
I know I should use a body-parser but don't know how and which one?
This is the Jade template:
extends layout
block content
.jumbotron
h1 Calculator
form(action='/calc',method='post', id="tableForm" )
p
select(name="lstSelect", id="lstSelect", size ="5")
option(value='one') One
option(value='two') Two
option(value='three') Three
p
input(type='text', name='txt1', id='txt1')
p
input(type='submit' name='StdDev', value='StdDev')
This is the NodeJS file:
//"use strict";
var express = require('express');
var routes = require('./routes/index');
var api = require('./routes/api/index');
var http = require('http');
var path = require('path');
var app = express();
var bodyParser = require('body-parser');
var multiparty = require('multiparty');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
app.post('/calc', function (req, res) {
var lstSelect = req.body.lstSelect; <- undefined
var form = new multiparty.Form();
form.parse(req, function (err, fields, files) {
// fields fields fields
var x = 1; <- bp never reached
});
var b = req.body; <- only txt1 element is here
});
EDIT: big flaw. Selected value is in request.body BUT I still need whole list. I need array of Select box values.

The select doesn't have any option elements, so it's skipped when submitting. The following should fix it;
extends layout
block content
.jumbotron
h1 Calculator
form(action='/calc', method='post', id='tableForm')
p
select(name='lstSelect', id='lstSelect', size='5')
option(value='one') One
option(value='two') Two
option(value='three') Three
p
input(type='text', name='txt1', id='txt1')
p
input(type='submit' name='StdDev', value='StdDev')
Also fixed some indentation so your input elements are inside the paragraphs.

Related

How do I display ejs data on html file?

I want users to fill out a form embedded a section of an HTML website, and have their submitted responses be updated every time on the same HTML file, rather than displaying their responses on a separate output.ejs file. I just don't know how beyond this point. What would I change in my server file?
var express = require('express')
var app = express()
var formdata = [];
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: true });
app.use(urlencodedParser);
app.get('/', function (req, res) {
res.render('index');
})
app.use(express.static(__dirname + '/public'));
app.set('view engine', 'ejs');
app.post('/processform', function(req,res) {
let data = new Object();
data.street = req.body.street;
data.pet = req.body.pet;
formdata.push(data);
let passedindata = new Object();
passedindata.formdata = formdata;
res.render("output.ejs", passedindata);
});
I would make another API endpoint that return formdata. After the user successfully post a response, instead of rendering output.ejs, have your form page make this API call to get the newly updated formdata, then process on the frontend as you please.

Displaying data from api array in node to a list in pug

I want to display data from the api to my pug page
eg display car park names
Index.js below
var request = require('request');
var express = require('express');
var app = express();
var endpoints = require("./endpoints")
app.set('view engine', 'pug');
app.get('/', function (req, res){
request.get('http://data.corkcity.ie/api/action/datastore_search?resource_id=6cc1028e-7388-4bc5-95b7-667a59aa76dc',
function(error, response, body){
var carPark = JSON.parse(body);
var carParkAll = carPark.result.records;
res.render('home', { parking: body});
});
});
app.listen(3000, function(){
console.log('3000');
})
home.pug
doctype html
html
body
p #{parking}
endpoints.js
(function (){
'use strict';
module.exports = {
parking: "http://localhost:3000/",
};
}());
Which displays
all of the data
Basically i want to show a list of all the car parks.
I am only learning this so i am still very much new.
Would love any form of feedback, cheers!
What you want is to iterate over the items using one of pug's iteration options: https://pugjs.org/language/iteration.html
Something like this:
ul
each park in parking
li= park
The same can be applied to more complex objects:
each park in parking
div.park_item
p park.name
p park.spaces
p park.price
The each keyword is pug's way of iterating over an array, where park will hold the object during each loop. Therefore you can access the object's properties inside the each loop using park.name, etc.

How to use a site to work on localhost with the help of node.js?

I am learning node.js where i am trying to use Google webpage to work on my localhost where its menu items to be removed but its search functionality should work on localhost as it works on website. This I tried working to use google on localhost but on localhost it shows "Can not Get", is this a kind of error or am i doing wrong please guide me that how i can achieve what i want to work. I am using node.js ver5.9.1 on XP.
Thanks in advance.
search.js
var express = require('express'),
app = express();
var bodyParser = require('body-parser');
compression = require('compression');
var NLTunnel = require('node-local-tunnel');
var options = {
remoteHost : 'http://www.google.com/',
localBase : 'http://localhost:3000'
};
NLTunnel.client(options);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(compression());
app.use(express.static('assets/'));
app.listen(3000);
var express = require('express'),
app = express(),
bodyParser = require('body-parser'),
compression = require('compression'),
http = require('http'),
server = http.createServer(app);
app.use(bodyParser());
app.use('/', express.static('public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(compression());
server.listen(3000);
Try this. This is working on my machine.
I have tried using request and cheerio but i am getting only html page and no any css or js page (if there) and search function is also not working. Is this right to work on and how we can make search functionality to work as usual on localhost.
var httpobj = require('http');
var request = require('request');
var cheerio = require('cheerio');
var all_html;
var url = 'https://www.google.co.in/?gfe_rd=cr&ei=dVHeVuLuG-uK8QeCk6vICw'
request(url, function (error, response, html) {
var $page = cheerio.load(html);
all_html = $page("html");
});
httpobj.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(all_html + ' ');
res.end('');
}).listen(8124, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/');

Node JS Express all requests showing 404

All requests are showing GET / 404 8.128 ms-13 in console.
I have posted the code below, there is no error in the code. I can run other NodeJS applications. But this is showing 404 in console. It is not even showing the fav icon. It worked once showing Cannot GET / error and the fav icon was visible at that time.
'use strict';
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var favicon = require('serve-favicon');
var logger = require('morgan');
var port = process.env.PORT || 8001;
var four0four = require('./utils/404')();
var environment = process.env.NODE_ENV;
app.use(favicon(__dirname + '/favicon.ico'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(logger('dev'));
app.use('/api', require('./routes'));
console.log('About to crank up node');
console.log('PORT=' + port);
console.log('NODE_ENV=' + environment);
switch (environment){
default:
console.log('** DEV **');
app.use(express.static('./src/client/'));
app.use(express.static('./'));
app.use(express.static('./tmp'));
app.use('/app/*', function(req, res, next) {
four0four.send404(req, res);
});
app.use('/*', express.static('./src/client/index.html'));
break;
}
app.listen(port, function() {
console.log('Express server listening on port ' + port);
console.log('env = ' + app.get('env') +
'\n__dirname = ' + __dirname +
'\nprocess.cwd = ' + process.cwd());
});
According to http://expressjs.com/starter/static-files.html I think that your route here app.use('/*', express.static('./src/client/index.html')); will use ./src/client/index.html as the base path and append whatever you provide to find a file. For example
/some-file will look for ./src/client/index.html/some-file which is obviously not existed
In case you want to understand it more, the static middleware use https://github.com/pillarjs/send internally to stream file
So you can do this
app.use('/*', express.static('./src/client'));
It will, by default, set / to src/client/index.html, you can change that behaviour by setting index option as specified here https://github.com/expressjs/serve-static
If you want to redirect /* to ./src/client/index.html do this
// first set the static middleware
app.use('/public', express.static('./src/client'));
// then use redirect
app.get('/*', function(req, res, next){
res.redirect('/public/index.html');
});
This setup will redirect everything to public/index.html. If you want to add APIs or other routes, put it before the app.get('/*')

node.js express app jade templates not rendering

I'm trying to create a cluster server with socket.io and express.js I'm following various tutorials on the internet as well on youtube.
What I have at the moment is this code in my app.js:
var cluster = require('cluster');
if (cluster.isMaster) {
var cpuCount = require('os').cpus().length;
var workers = [];
for (var i = 0; i < cpuCount; i++) {
workers[i] = cluster.fork();
}
cluster.on('exit', function (worker){
for (var i = 0; i < workers.length; i++) {
if (worker.process.pid === workers[i].process.pid) {
workers.splice(i, 1);
}
}
for (var i = 0; i < cpuCount - workers.length; i++) {
workers.push(cluster.fork());
}
});
} else {
/**
* Module dependencies.
*/
var express = require('express');
var routes = require('./routes');
var http = require('http');
var path = require('path');
var app = express();
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
var server = http.createServer(app);
var io = require('socket.io').listen(app.get('port'));
}
When I go to http://localhost:3000/ I get the response:
Welcome to socket.io.
In my previous test scripts I didnt have this issue and my jade templates were being rendered fine. Could someone explain why is this happenning?
Furthermore in my routes directory I have the script: index.js with this code:
/*
* GET home page.
*/
exports.index = function(req, res){
res.render('index', { title: 'Express' });
};
Finally in my views folder I have layout.jade with:
doctype 5
html
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
body
block content
and index.jade with:
extends layout
block content
h1= title
p Welcome to #{title}
It seems that the problem was in the final lines of app.js
this fixes the issue:
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(app.get('port'));
Sorry for any inconvenience.

Categories

Resources