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

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.

Related

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

Run a server side Javascript version with Express

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.

Prevent reloading of angular component while refreshing page

I have Single Page Application website, written in angular 4+. I have so many components likes as FilterComponent, SideBarMenuComponent, HeaderComponent, FooterComponent, etc.
I want to prevent reloading of SideBarComponent to be initiated of ngOnInit when user refresh whole page. How can I do prevent ngOnInit method not to run for only SideBarMenuComponent so that whatever is user selected in side bar menu, it wont get removed.
Please let me know if you did not get understand in comment section.
When user reload your SPA application then your every component must reload.
You can store user's selected menu in local storage. So when user reload your app you can check previous selected menu
I think you can achieve this using Angular pushState:
https://angular.io/guide/router
As a matter of fact, as a coincidence, the link from the Angular documentation I included does exactly this too. If you go to the link above and refresh the page, the navigation on the left of the page stays the same, even if the page reloads.
Note that pushState requires server side support, meaning that the server needs to return the Angular app index.html instead of a 404. This is slightly more complex issue, but if, like me, you serve your Angular app from a Node.js backend (which is not an amazing idea), you can use this script:
const express = require('express');
const serveStatic = require('serve-static');
const compression = require('compression');
const port = process.env.PORT || 3000;
const domain = process.env.DOMAIN;
function ensureDomain(req, res, next) {
if (!domain || req.hostname === domain) {
// OK, continue
return next();
}
// handle port numbers if you need non defaults
res.redirect(`http://${domain}${req.url}`);
}
const app = express();
// at top of routing calls
app.all('*', ensureDomain);
app.use(compression());
// default to .html (you can omit the extension in the URL)
app.use(serveStatic(`${__dirname}/dist`, {
'extensions': ['html'],
etag: true
}));
app.get('*', function(req, res){
res.sendFile(`${__dirname}/dist/index.html`);
});
app.listen(port, () => {
console.log('Server running...');
});
Note the lines:
app.get('*', function(req, res){
res.sendFile(`${__dirname}/dist/index.html`);
});
which serve any request that hasn't been handled, with index.html (effectively instead of a 404).

How to get the params in a Express route when I am using app.use() for the home page in my server

So, basically I have this middleware on my server.js file: app.use(express.static(__dirname + '/public')) for the home page.
It's possible to show the same home page when a user hit this route: app.get('/ref=:refId') and still show localhost:3000/ref=Asldoe2231sSLexe2 in the address bar?
Now I know that I can achieve this behavior using query string like so: localhost:3000/?ref=Asldoe2231sSLexe2 and then get the query string using req.query.ref on the server, the problem is I cannot use app.use(express.static(__dirname + '/public')) directly if I have this route app.get('/', (req, res) => {.... How can I solve this?
My goal is either grab the refId value on the client, send it to the server and check if exists in the database or check it directly as soon as the client hit the route, I rather prefer the second option which is a cleaner way of doing it.
What you want to do don't have a relationship with
app.use(express.static(__dirname + '/public')). It is used for giving the path to static files such as CSS, images in your application.
You can get refId by req.query.ref and pass it to the page you are rendering.
One way is :
res.locals.refId = req.query.ref and in your view use refid
Second way is :
res.render('<file_you_are_rendering>',{refId:req.query.ref})

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.

Categories