How do I display ejs data on html file? - javascript

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.

Related

Pass IDs from POST request to separate endpoint

I'm teaching myself Nodejs and am trying to populate a page with a list of nearby businesses' opening and closing hours from Yelp's API. I created a POST route to my page in Express, calling the Yelp API using the Yelp Fusion client. I am able to gather an array of ids which must be used in another endpoint in order to fetch the hours of operation, however I keep receiving TOO_MANY_REQUESTS_PER_SECOND errors when do this, despite setting the limit in the request.
Server.js
var express = require("express");
var app = express();
var yelp = require("yelp-fusion");
var bodyParser = require("body-parser");
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.urlencoded({extended: true}));
app.set("view engine", "ejs");
let client = yelp.client("API_HIDDEN");
app.get("/", function(req,res){
res.render("landing");
});
///Initial request made to obtain business ids
app.post("/", function(req, res){
client.search({
term: 'cafe',
location: 'Oakland',
limit: 20
}).then(response => {
var ids = [];
var businesses = response.jsonBody.businesses;
var idName = businesses.map(el => {
ids.push(el.id);
});
// request separate endpoint, passing ids from the ```ids```array
for(var x = 0; x < businesses.length; x++){
client.business(ids[x]).then(response => {
console.log(response.jsonBody.hours);
})}.
res.render("search");
}).catch(e => {
console.log(e);
});
})
app.listen(3000);
I have tried calling client.businesses[id] both inside and outside a for loop but this resulted in errors too. I am confused on the behaviour of this as I am only making 20 calls, far below the minimum, but also how to possibly pass the ids if not for an array as I have run out of ideas. Thank you in advance for your help.
Spread out the api calls over time.
var delay = 1.1 * 1000; // 1.1 seconds in milliseconds
for(var x = 0; x < businesses.length; x++){
setTimeout(function(i){
client.business(ids[i]).then(response => {
console.log(response.jsonBody.hours);
});
},delay*x,x);
}

Pass a parameter to another JavaScript and run the script

Send a parameter(URL) from another script through recursion to this script.
var express = require('express');
var request = require('request');
var cheerio = require('cheerio');
var mongodb = require('mongodb');
var app = express();
var MongoClient = mongodb.MongoClient;
// Connection URL. This is where your mongodb server is running.
var murl = 'mongodb://localhost:27017/getData';
url = '';
app.get('/getData', function(req, res){
firstCall(req,res)
//console.log("cookie",req.cookies);
})
var firstCall = function(req, res, data){
console.log("URL: ", url);
res.send('Check your console!');
}
app.listen('3000')
console.log('Magic happens on port 3000');
module.exports = function(app) {
app.get('/getData', function() {});
};
I want this code to act as backbone or logic board. And some other file should be able to trigger this logic board file by adding the URL to this file.
Like we pass parameters to function to call. How do I do it here.

Parsing html elelments on form POST in NodeJS

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.

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('/*')

Categories

Resources