Run a server side Javascript version with Express - javascript

recently i got into web programming and i started to learn javascript,node.js and express.js and my goal is to run a server side javascript function(to be more accurate a function to search something in a mysql db) when a button got pressed on a html.
My dir structure is like this : A main dir, containing a dir "page". Page containing server.js, dbFunctions.js and "public" dir. Public containing a index.html,style.css and some images.
Server.js :
var express = require('express');
var app = express();
var path = require('path');
var port = 8888;
//allow to use static files
app.use(express.static("public"));
//start server
app.listen(port);
console.log("Server running on port" + port);
HTML Example
<html>
<head>
<title>Test html</title>
</head>
<label for="key">Valid key:
<input id="key" name="key" required>
</label>
<input type="checkbox" name="test" value="testval" checked>
<button type="button">Button</button>
</html>
So basically the HTML got a input field,a checkbox and a button, and if the button is clicked it should run a function from dbFunctions.js with parameter(taken from the field and the checkbox as bool) on server side
I heard something about ajax calls etc but those explanations are usually very confusing. Is there any "hello world" example?
Greetings.

Sounds like you're quite new to JS so I would recommend breaking this down into two components.
One is your server side code and the other is your front end code. As you mentioned you find the front end code confusing, I would suggest coming back to that, once you have got your server side code working.
To make things easy, you could use something like express generator which boiler plates everything for you.
You can then follow this guide which will show you how you can set up a route which you will be able to make some sort of request to. Like a POST, GET or PUT request (which is what your front end AJAX code will eventually make a call to).
My advice would be to try get your route working and testing it with something like Postman so you don't have to worry about building the front end simultaneously.
When you are happy with the back end, you can start look into how to make requests from the browser to hit your new back end route you have set up.

Yes, check out this amazing post
https://medium.com/#adnanrahic/hello-world-app-with-node-js-and-express-c1eb7cfa8a30
This is an example hello world node js application with express js.

First you need to make your html page call your server. To do that you can :
Place your button inside a form and set your form action equal to /getHelloWorld
Create a javascript script and call your /getHelloWorld in ajax
In your server you need to catch route like this :
Server.js :
var express = require('express');
var app = express();
var path = require('path');
var port = 8888;
//allow to use static files
app.use(express.static("public"));
app.get('/getHelloWorld', (req, res) => {
res.send('hello world !');
});
//start server
app.listen(port);
console.log("Server running on port" + port);
with this your server will return Hello World When you'r calling this road : /getHelloWorld.
Then you just need to replace code inside route catch by a code to call your DB and return your DB response.

Related

making variables completely invisible to user until he does a specific thing

I have 3 main code classes:
1) node.js (running express)
2) the index.html (which loads the moment we enter the site)
3) sck.js which does something (I will explain it after the first and second files)
what I basically do is, I want the user to click on a button. and then the server will output on the page (HTML) or, alert (does not matter to me)
a specific line/word...
I am going literally crazy, I've searched everywhere...
I don't want the user to see the secret word until he clicks the button. not even in the source code (F12) !!!
sck.js is just a jquery that listens to a button click.
app.js:
const express = require('express');
const path = require('path');
const app = express();
//Set a static folder
app.use(express.static(path.join(__dirname, 'public')));
app.listen(3000, ()=>{
console.log(`starting server port 3000`);
} );
in index.html there is just a button, waiting for the user to click it.
TL;DR : how do I make a variable COMPLETELY invisible for the user, until he clicks a button?
I thought about saving the secret in app.js (because the user cant see whats written there...) and then passing it somehow to the html... but I cant!!!
doesn't it suppose to be easy? it sounds like that .... :(
Thanks!!
A super simple way. Add a route to your express app:
app.get('/getflag', function (req, res) {
res.send('theflag');
});
Add a link to your HTML
Get Flag
Click the link, you will be taken to a page with 'theflag' displayed.

Socket.io: io is not defined

So, I am trying to get data on my node.js file instead of directly getting it on my JS file.
I a using Socket.io 2 here, Below is a snapshot of my code and this is also the first time I am using Websocket with Node.
I am doing something like
var socket = require('socket.io')
//Home Page
app.get("/", function(req, res) {
var cryto = io.connect("https://xyfz.com/);
cryto.on('trades', function (tradeMsg) {
console.log(tradeMsg);
});
res.render("index");
});
I also tried something like
var io = socket("https://abc.io/");
and
var socket = require('socket.io')
var io = socket();
which was throwing errors like server.listeners is not a function and io.connect is not a function.
I am certain that I messing up stuff here so can someone guide me about the correct way of doing it?
Two things which are wrong .
First Consider using Socket.io-client instead of Socket.io.
Second and very much important.
Never ever make API calls inside your routes. This will trigger a API call everytime user opens your website or webpage
You can also expect an error "Unexpected headers" or something like that.
Always, Try do declare it outside any routes in your NodeAPP.
Same goes for socket.io as well

app.post not working! "Cannot GET /up"

i have a button in a /index.jade file that when pressed it executes
window.location.replace("https://upload-andsize.glitch.me/up") function.
the only thing it does is to redirect me from / to /up so far so good.
and if i make a get request all works fine but!..
a post request will not work
app.post("/up",function(req,res){
res.send("hello-world")
})
//will return Cannot GET /up
server code
var express = require('express'),
app = express();
app.set("view engine","jade")
app.use(express.static('public'));
app.get("/",function(req,res,next){
res.render(__dirname+"/views/index.jade",{})
next()
})
app.post("/up",function(req,res){
res.send("hi")
})
var listener = app.listen(process.env.PORT || 3000, function () {
console.log('Your app is listening on port ' + listener.address().port);
});
jade code
html
script(src= "client.js")
title!=title
h1 upload a file and see its weight
input(type="file" id="myfile")
input(type="button" onClick="send()" value="submit")
client code
function send(){
window.location.replace("https://upload-andsize.glitch.me/up")
}
ok the problem was a lack of understanding how does the routs work
the solution is that im not sending a post request but a get request
thats why im getting an error
changed the html to
form(action="/up" method="POST")
input(type="file" id="myfile")
input(type="submit" value="submit")
and it all work well hope it will help others in future
Please add app.get('/up',(res,req)=>{}) method in your server code.

Error NodeJS : Cannot get

I'll try to be as clear as I can be. So I'm trying to make a little plateform. I would like that someone connect to the page (in localhost) and then, have the possibility to click on a button, and this button will redirect him to another html page.
So I have a project folder with my "initial" html, my app.js file, and the other html file, which should show itself when clicking on the button.
The server works like this :
var application = require('express')(),
server = require('http').createServer(application),
io = require('socket.io').listen(server),
ent = require('ent'),
fs = require('fs');
application.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
and then, I have the button :
<input type="button" value="blah">
When launching "node app.js" on the terminal, I go on the page, click on the the button and then I got the error "Cannot GET /pfc.html".
Sorry if I'm quite not understandable, I hope someone will understand me.
Thanks and have a nice day!!
You wrote some code to tell your server what to do if the browser asks for /
application.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
Then you wrote a link:
<a href="pfc.html"
which makes the browser ask for /pfx.html.
You haven't written anything in the server side code to tell it how to respond to a request for that. You've only told it how to respond to a request for /.
You could write something similar (application.get('/pfx.html',...) or find some existing middleware for handling static files.
If you have multiple HTML files like pfc.html, you can use
application.use(express.static('public'));
and keep all your html files (including pfc.html) in a folder named public and all those html files that you serve like:
you can look for them at public/pfc.html and such. If the file exists, then the application won't return stuff like Cannot GET /pfc.html and you won't need to write explicit routes for all of them.

NodeJS Modulization

So, I was told that passing around the request and or response variable in nodeJS is "bad practice". But this means that most of your code has to be in the server.js file, making it cluttered and kind of ugly.
How can you modularize your nodejs server, passing around req/res appropriately and be able to organize your code into separate files?
For example, I would like to split my socket routing, .get and .post into different files, but still be able to use the callback parameters like so:
app.io.route("disconnect", function(req,res) { <--- these params
db.query("UPDATE player_data SET online=0 WHERE id="+mysql.escape(req.session.user));
req.io.broadcast("event", {msg:req.session.username+" has logged out!"});
app.io.broadcast("reloadXY");
});
As of right now they're all in one file and I don't like that.
I think what the person meant by 'passing around' was something like this (in plain express):
app.get('/kittens', function(req, res) {
db.doAthing(req);
updateSomethingElse(res);
upvoteThisAnswer(res);
});
That is, passing around the two variables beyond the first function. This is bad because it becomes increasingly difficult to figure out where the call actually ends. One little res.end(500) in updateSomethingElse can cause the whole house of cards to come tumbling down.
It's perfectly ok (in fact, standard to the point of being the default in express) to declare that callback elsewhere (usually the /routes directory of your project.)
// app.js
var user = require('./routes/user')
, kittens = require('./routes/kittens');
// express stuff...
app.get('/settings', user.getSettings);
app.get('/fur', kittens.shed);
Then, in routes/user.js:
exports.getSettings = function(req, res) {
// Note how we're passing around properties of req/res, not the objects themselves.
db.getUserSettings(req.user.id).then(function(settings) {
res.render('settings', settings);
});
};
This video from TJ Holowaychuk (the guy who wrote Express and a ton of other Node infrastructure that we all use) helped me take Express modularization to the next level. Basically you can make individual apps in their own folders and consume them as middleware very easily. I have managed to extend this technique to socket.io with some tricks.
http://vimeo.com/56166857
You should not pass req and res to another modules but pass callbacks from another modules to route.
It should look like.
var someModule = require("./someModule")
app.get("/someAction", someModule.handleSomeAction) ;
If You want to have post and get in another modules You should pass reference to app (from express()) once to that module and operate on that.
For example :
var express = require("express") ;
var app = express();
var get_handler = require("./get_handler ")
var post_handler = require("./post_handler ")
get_handler.init(app);
post_handler.init(app);
and in post/get_handler :
var app;
exports.init = function( eApp){
app = eApp;
// operate on app
}

Categories