Express.js and form validation - javascript

I'm tring to create a simple node- with express.js script that will sum 3 numbers.
On index I have this:
index.jade
!!! 5
html
head
title Test
body
form(name='form1', method='post', action='/')
label(for='1')
input#1(type='text', name='1')
label(for='2')
input#2(type='text', name='2')
label(for='3')
input#3(type='text', name='3')
input(name='submit', type='button', value='submit')
#result
and also i'm now writing the serverside - app.js with req and res object but how to return a result... also result = 1id + 2id + 3id
app.js
var express = require('express');
app = express.createServer();
app.use(express.bodyParser());
app.post('/', function(req, res){
var i = req.param('1', null);
var j = req.param('2', null);
var k = req.param('3', null);
var r = i+j+k;
res.send(r);
});
How I to send results (r) into div id Result on index.jade... so how to return result to index.jade
also here is pastebin code: http://pastebin.com/J9MRFCaE ... i'm new to node and express and sorry for stupid question...

It's simple, just call your "index.jade" rendering passing your data (instead of 'res.send(r);') :
res.render('index', {
result: r
});
And display "result" variable in your jade file :
#result #{result}
Additional information on jade code and express rendering

Related

Accessing server values in javascript file?

EDIT: Forgot a piece of code when taking stuff that was relevant
I want to work with the "jsonData" value from my server in my javascript file, but i don't know how to get the values there?
server code:
var express = require('express');
var app = express();
app.use(express.static('public'));
var Amadeus = require('amadeus');
app.set('view engine', 'ejs');
app.listen(8080);
app.get('/hotels', function(req, res){
var searchTerm = req.query.cityCode;
amadeus.shopping.hotelOffers.get({
cityCode: searchTerm
}).then(function(response){
var jsonData = JSON.parse(response.body);
var output = "";
for(var i = 0; i < jsonData.data.length; i++){
output+= "Name: " + JSON.stringify(jsonData.data[i].hotel.name) + "\t";
output+= "Rating: " + JSON.stringify(jsonData.data[i].hotel.rating) + "\t";
}
res.render('pages/onestar', {jsonData: output});
}).catch(function(error){
console.log(error.response); //=> The response object with (un)parsed data
//console.log(error.response.request); //=> The details of the request made
console.log(error.code); //=> A unique error code to identify the type of error
});
});
JavaScript attempt that i have so far:
$(document).ready(function(){
$('#searchbutton').submit(function(){
event.preventDefault();
$.get('xxxxxx', function(jsonData){
console.log(jsonData);
});
return false;
});
You need to send something back from your express server program to the web browser. There are lots of methods on the res object to do that.
Replace
var jsonData = JSON.parse(response.body);
with
res.status(200).json(JSON.parse(response.body))
You could also send back the JSON text in the response.body directly rather than parsing it first, only to tell express to stringify it again. But the req.json() function also sets the Content-Type header on the response to the web browser so it knows it's getting JSON. With respect, that's a little complex for your apparent present level of understanding. Keep it in mind for a later optimization when you get your code working.

Passing array from js to Nodejs

I have an array that is initialized when my user makes an input. I want that array to be passed to the nodeJS side of things rather than just stick around in the frontend. All the other variables that I am grabbing are named "net[object]" so I can grab them all in an array when necessary. The array I created only ever has one element being displayed in an input group at a time. If you need a better visual, go to "#nodes in hidden layer" for the neural net demo here: http://irisml.org/demos/
I am a complete noob when it comes to web development, so please be patient with me :)
//JS code creating array
numLayers.addEventListener('input', function(){
nodesArray.length = 0
num = numLayers.value;
nodes.innerHTML = '';
initialized = true;
for(var i = 1; i < num - 1; i++){
var node = document.createElement("option");
var textnode = document.createTextNode("Nodes in Hidden Layer " + i);
node.appendChild(textnode);
document.getElementById("nodes").appendChild(node);
nodesArray.push(1)
}
});
//Current NodeJS code
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
router.post('/', function(req, res){
console.log(req.body.net)
});
You can use "fetch" to send a post request to the backend.
//frontend
let nodesArray = [1,2,3];
let body = JSON.stringify({net:nodesArray});
fetch("/",
{method:"post",
body:body,
headers: {
'Content-Type': 'application/json'
}});
Your backend needs to listen on a port
//backend
var express = require('express');
var app = new express();
app.use(express.json())
app.listen(3000, console.error); //listen on port http://localhost:3000
app.use('/static', express.static(__dirname + '/static')); //OPTIONAL host static/index.html
app.post('/', function(req, res){
console.log(req.body.net, 'net');
res.send("RESPONSE");
});

How to replace .js file content based on number of calls

I do have a site which calls a javascript file located outside of my site. What i want is that it's content gets replaced once every X calls repeadetly.
First i thought i could use Node.js and use a function like this:
var express = require('express');
var app = express();
var path = require('path');
var Chance = require('chance');
var chance = new Chance();
app.get('/get-javascript-file', function(req, res) {
if (chance.integer({min: 1, max: 10}) == 1) {
res.sendFile(path.join(__dirname + '/someFile.js'));
} else {
res.sendFile(path.join(__dirname + '/someOtherFile.js'));
}
});
app.listen(80);
But as you can see the script itself replaces js file with another one. I was hoping i could do somehow the same with just one js file.

Run the script in node.js only after user select file in html

I am using node.js to launch a serve so that my html can communicate with R code. But I am facing a problem on node.js. In my html page, I have a browse selection button, user can use it to choose the data file they want to read into html and node.js will pass the file name to R, so R code will read data from the selected data file and then run the analytics model. But as i only have very basic knowledge of Node.js, so currently, r code would run only when I open the followling link "localhost:3000/vis/rio". So my question is how to make node.js run the R code in background automatically when the data file has been selected. Thank you very much for your help in advance.
Here are my codes:
Javascript-(sending the file name to node.js):
var dataset,availableTags;
function handleFileSelect(evt) {
var file = evt.target.files[0];
$.ajax({ //getting the file name and update to node.js
type:'post',
url:"/getFileName",
data:{filename:file.name}
});
Papa.parse(file, { //papa is a library I used to read csv file
header: true,
dynamicTyping: true,
complete: function(results) {
dataset=results.data;
}
});
}
$(document).ready(function(){
$("#csv-file").change(handleFileSelect);
});
Node.js script:
serve.js:
var express=require('express');
var path = require('path');
var vis = require('./routes/vis');
var index = require('./routes/index');
var bodyParser=require('body-parser');
var app=express();
require('./routes/main')(app);
app.get('/vis/rio',vis.rio); **//this is a package used to get connection with Rserve**
app.set('views',__dirname + '/views');
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.urlencoded());
app.post("/getFileName",index.getFileName); **//this is the script to get the file name, it is from index.js**
var server=app.listen(3000,function(){
console.log("Express is running on port 3000");
});
index.js // this is the js file for getting file name
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res) {
res.render('index', { title: 'Express' });
});
getFileName=function (req,res){
global.filename=req.body.filename; **//this is the global variable which stores the file name**
res.send('true');
};
module.exports = {router:router,getFileName:getFileName};
vis.js // this is the file used to connect with Rserve and pass the name to R code
var rio = require("rio");
var arg={};
exports.rio = function(req, res){
arg={names:[global.filename]};
console.log(arg);
options = {
entryPoint:"nameoffile",
data: arg,
host : "127.0.0.1",
port : 6311,
callback: function (err, val) {
if (!err) {
console.log("RETURN:"+val);
return res.send({'success':true,'res':val});
} else {
console.log("ERROR:Rserve call failed")
return res.send({'success':false});
}
},
}
rio.enableDebug(true);
rio.sourceAndEval(__dirname + "/Rcode/test.R",options);
};
It looks like you aren't calling out to /vis/rio at any point when you make the call out to your server.
You'll either need to make a second call on the client side to /vis/rio or if you want to use that section, you can import/require the module in index.js and include it in getFileName and just call out to the function there before you return the file. I'm not super familiar with rio, but I don't see any access point in your code to that function.
Edit: If I understand what you're trying to do correctly, you can always make a second request (to /vis/rio) in the success callback of your first ajax call.

How to render an array in an html file? - Node.js, ejs

I'm working on a project, which will use given coordinates from a txt file and graph them.
My problem right now: I'm trying to use ejs to render the coordinates into my html file, but it just isn't working right. Ejs always just renders: undefined.
Here is the code:
var http = require('http'),
fs = require('fs'),
express = require('express'),
app = express();
app.use(express.bodyParser());
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use(express.static(__dirname + '/public'));
//Readerfunction
function readLines(input, done) {
//.....
function done(arr) {
var obj = {};
var key1 = arr[0][0];
var key2 = arr[0][1];
obj[key1] = [];
obj[key2] = [];
arr.shift();
arr.forEach(function (item) {
obj[key1].push(item[0]);
obj[key2].push(item[1]);
});
console.log('X:', obj[key1]); // all the variables are logged correctly.
console.log('Y:', obj[key2]);
app.get('/', function(req, res) {
res.render('graph.html', {cordinates: obj});
});
app.listen(8080, function() {
console.log('Server running at http://127.0.0.1:8080/');
});
}
In the html file:
<%= cordinates.obj %>
I hope you can help me, solve this problem! :-)
Greetings,
JS
Well, I think here is the problem: you are passing obj to render as coordinates, so you should use coordinates variable in your template directly, no it's obj property, which is non-existent. I'm not sure if it will be rendered as proper array though, maybe you'll need a loop to print it's elements.

Categories