Prevent reloading of angular component while refreshing page - javascript

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).

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.

How express.route determined route

I'm start learning about Node.js (with Express.js) and React.js. So I have some question about Express Router
Let's see my part of code
server.js
const app = express();
const apiRouter = require("./Routes/apiRoute");
app.use("/api", apiRouter);
app.listen(3000, () => {
console.log("application run on port " + 3000);
});
/Routes/apiRoute.js
const express = require("express");
const router = express.Router();
router.route("/user/:id")
.post((req,res)=>{
// Do something
})
router.route("/user/status")
.post((req,res) => {
// do something
});
So. My question is How express route determined which method to go.
From my example code if I send POST request like this http://localhost:3000/api/user/status
express router will see status is :id right ?
in the otherhand if I move route for /user/status up it's will go as I expected right ?
Thank you.
Express matches route in chronological order.
Express starts to match URL with the first route that has been declared in the script and then moves to the next if it does not match. This is because of the fact that Express is a Javascript framework. The function you pass to a route i.e. (req, res) => {...} is actually a js callback function that would be called if the user hit the route matching the corresponding string declared. And in Javascript, the callback that is set first for an event is called first because these callbacks are maintained in a queue. A queue is FIFO as we all know.
If you want both "/user/:id" and "/user/status" to work, you would have to declare the later one first in your code and then the first one.

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})

How can I dynamically assign a database path in Express.js based on login?

I have a backend service that I would like to use as a single point of entry for my web application, and dynamically assign a database path based on the user login.
I realize that this is not a scalable solution. I intend to use it during a testing period with several clients (accessing the ALPHA database), and also setting up a demo (accessing the SAND database).
I have the following module that I have written as a simple test to see if the login is for the demo user, all other logins will go to the other resource:
config.js
var express = require('express');
var app = express();
module.exports.dbPath = function (login){
console.log('login - ', login);
if (login === 'demo#mysite.com'){
return process.env.DB_SAND;
} else {
return process.env.DB_ALPHA;
}
};
My question is, how can I manage each unique login and assign a globally accessible reference for that session to direct each user session consistently to the correct database?
Am I overcomplicating this? If there is a different approach that would be a better practice I would welcome a suggestion in another direction.
I would use it as a middleware, and attach it to the req object for each user, something similar this:
module.exports = {
dbPath: function(req, res, next){
var login = req.body.login;
console.log('login - ', login);
if (login === 'demo#mysite.com'){
req.dbPath = 'DB_SAND';
} else {
req.dbPath = 'DB_ALPHA';
}
next();
}
};

Node & Express + jQuery: After authenticating save for session

I managed to make the user able to authenticate using name/pass. What I'm trying to achieve is, a disabled dropdown, when he authenticates, it gets enabled, then he can access files through the dropdown list. All of that I managed to make, one thing I'm puzzled with is how can I check if he already authenticated or not? So no one would inspect the html code and get access to the files.
I need a way to identify if a client (jQuery) has authenticated or not, something like session variables that ends with closing the page.
EDIT: I need it to be secured, I want to store a boolean that will allow the client to view all the log files.
Store this boolean in an Express session, and select which page to send to the client.
// enable session support
app.use(express.cookieParser());
app.use(express.session({
secret: 'secret key for signed cookies'
}));
app.get('/foo', function(req, res) {
req.session.authenticated = true;
});
app.get('/bar', function(req, res) {
if (req.session.authenticated) {
// send page with files
} else {
// send page without files
}
});

Categories