Combining Different Modules in NodeJs - javascript

I have Created Separate Working Modules in nodejs
Login
Chat
File sharing.
I want to combine them all. Like after getting successful login i want it to redirect to chat module. Right now i can redirect to static html page after login.
app.post('/login', passport.authenticate('local-login', {
successRedirect : '/profile', // redirect to the secure profile section
failureRedirect : '/login', // redirect back to the signup page if there is an error
failureFlash : true // allow flash messages
}));
Note: Now If i have to run any module i have to compile it individually and run it on localhost.

Assuming that you are using Express Framework, for the successRedirect , instead of redirecting the user to '/profile' route, redirect him to (lets say) '/chat' and define the app.get('/chat,callback) route in the same file , or export your chat module and require it in the file that you are using for authentication/login

Related

Cookies dont get stored because of path with req.cookie

Hello I got a similar problem as this one : Cookies don't get stored in localhost but the difference is that for me it works when I put path:'/' (the default path) and path:'/login' (which is the current client side page when the cookie is trying to be stored at the end of the login process) but it doesn't for any other path.
res.cookie(`api`,token,{
domain:'localhost',
path:'/account',
expires: new Date(Date.now()+7*24*60*60*1000),
httpOnly: true
});
My server is on port 3000
Edit: I need to add that I have a middleware like this in my app.js file
app.use("/auth/", authRoutes);
authRoutes is the module file where I put the different routes like /login and /register. So when I submit the login form it is calling the /auth/login route server side which will execute the login function where I try to create the cookie after all the email/password verifications. I just tried path as '/auth' in the res.cookie function and it actually worked. Could that be the problem ? That I am trying to create a cookie in a function that is considering '/' as /auth/ because it is a middleware. I don't know if it's clear but I was thinking maybe it is somehow related even if I wouldn't understand why.
Edit 2 : In my app, Express serves static files of my react front end app. What I want to do is put a httponly cookie on the user's browser after login that will be sent back to server only when user visit the '/account' page to verify the user's identity and if he is still connected.

How to separate the frontend routing from backend endpoints?

I have an express server which handle some routes
/users/login
/users/register
/orders/add
and so on..
serving a static files, in the default route
"/"
so, if user navigated to domain.com for example
it will navigate to that static files
these static files are a react frontend app
the default url "/" will navigate to a login page
and "/dashboard" will navigate to another page
what actually happen, is there's kind of conflict between the backend and frontend routes
for example
if user navigated to "/dashboard"
the expected result is to navigate him to the frontend page
what actual happen is "the backend handle that route not the frontend" and simply return : "I don't have that route (404)
What was in my mind is to navigate any not handled route to the frontend
using that code
app.get('*', async function (request, reply) {
return reply.sendFile('index.html')
})
however, not solved my problem

How to run middleware on each React page in express server

I'm running an express server and if no other certain URLS aren't met, the user is redirected to the React App:
app.get("*", verify, (req, res) => {
if (maintenance) {
return res.sendFile("./maintenance.html", { root: __dirname });
}
return res.sendFile(
path.resolve(__dirname, "../frontend/build", "index.html")
);
});
This successfully runs the verify middleware needed to check if the user making the request is logged in, if not it redirects them to another service for them to login.
I would've thought that since all URLS that are being used are going through the whole web app is going through this express server, the verify middleware would've been executed no matter what page the user is on. However, this middleware is only executed upon either opening the site on a browser that hasn't been to the site yet (not cached) or if the user force refreshes the page.
I'm new to React and this has led me to believe that React loads the whole app, and upon each change of page (for example from /home to /profile) it doesn't change the url, just loads the portion of the app that's already loaded and so no matter what page the user is on, express will always see that the user is only on the root domain.
How would I get pass this without doing any of this logic on the frontend side. E.g. run the verify function before each page on the react app is loaded into view
Since React is all client side rendering you will need to handle that middleware in your React router, not your Node router. On the frontend we call this "middleware" protected routes.
The overall point is, you will need to protect those routes on the frontend, as when you change a page in React, Node does not know about it (because React is client side rendered).

How to route a Node.js Single Page App?

I'm trying to design a Single Page App using Node.js that has multiple tabs, and on each tab can contain a number of images or scripts, so I'd like to prevent loading the content of every tab each time a user visits the page. So ideally when a user switches tabs the server would send the html which contains the images and scripts and the client would display that without reloading the page.
The reason I chose the SPA design is that outside the tabs would be a chat system amongst other things running in the background that I don't want to resend to clients each time a redirect happens.
So my question is what is the best way to send the html, or is there a better way in general that still uses the SPA design?
Would the best way be to send the html in the router to the client, then use ajax to prevent a page refresh and add new tab html and remove old tab html after that?
You can use Express.js with only one route.
This route could be called:
var app = require('express')();
app.get('/',function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
}
Note that:
This is a GET route
It just sends the file contents with sendFile
After that you can have many API routes to fetch the data for your tabs. I would recommend these routes to be like this:
app.post('/about',function(req, res) {
res.json({ data: "your data here" });
}
app.post('/contact',function(req, res) {
res.json({ data: "your data here" });
}
On these routes note that:
These are POST routes
Only a JSON is returned
SPA means "single page app", and you will only have a single HTML shell that a JavaScript framework will then handle the "pages" and HTML after that

Node.js and Express - Redirect after Login and Download

I have an express app that allows a user to login and download data files. There is also a home page after the login. If a user enters the URL to a specific file without logging in, the app will first ask the user to login, which is by design. However, after the user logs in, the file is downloaded without redirecting the user to the home page. I was wondering if there's a way to allow the user to login, redirect to the home page, and then download the file with one click after the user logs in. It's kind of confusing now because the user is stuck on the login page after successfully logging in and downloading the file. Below is a snippet of the code. I am using express 4.x:
app.get('/dat/:file(*)', routes.ensure_authenticated, function(req, res, next) {
var path = __dirname + '/public/dat/' + req.params.file;
res.download(path);
});
app.use('/', serveStatic(__dirname + '/public'));
// dat directory requests
app.use('/dat', routes.ensure_authenticated, serveIndex( 'public/dat', { icons: true }));
I can't think a way of doing it server-side only.
You could trigger client-side the redirection to the download.
Something like redirecting to /#download=link_or_id and parsing the hash with JavaScript to get the final download link (the link_or_id thing). Then, after the download is triggered, remove the hash from location so the download isn't triggered again when the user reloads the page.
Also, instead of using JavaScript, you could do something similar redirecting to /?download=link_or_id and server-side inserting a meta refresh tag inside <head>.
You could programmatically send an ajax GET request from the client side via a setTimeout or on document load, so it would be something like:
$(function() {
$.get('/dat/filename', function(){
//enter code here
});
}):

Categories

Resources