I have an express/react app which runs just fine, it is a single-page app. I needed to make some changes on the server side regarding authentication, but I noticed that running the express server my app was not serving the updated .get function. Any thoughts on why this might be happening?
Old function
app.get('/app/', (req, res) => {
res.sendFile(path.join(__dirname, 'build', 'index.html'))
})
New function:
app.get('/app/', async (req, res) => {
const authorized = await checkSession(req)
if (!authorized) { res.redirect('/login'); return}
res.send("OK")
})
I suppose I should get a plain OK as a response in the browser, but even changing the server port, browser or anything I can think of I get the old page. Any help is much appreciated.
Remove the trailing slash on the first parameter of app.get():
app.get('/app', async (req, res) => {
const authorized = await checkSession(req)
if (!authorized) { res.redirect('/login'); return}
res.send("OK")
})
try to remove async/await because when you use this checkSession return one promise and continue to execute the rest os the code in this case you have to wait the return of checkSession before verify if is authorized.
Related
I have the following code snippet made with express js
import serverless from 'serverless-http'
import express from 'express';
const app = express();
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.get('/api/info', (req, res) => {
res.send({ application: 'sample-app', version: '1.0' });
});
app.get('/jump', (req, res) => {
res.redirect('/api/info');
});
app.get('/explicit-jump', (req, res) => {
res.redirect('/dev/api/info');
});
app.post('/api/v1/getback', (req, res) => {
res.send({ ...req.body });
});
export default serverless(app)
If I deploy that code with serverless probably I will get an endpoint like https://my-api.some-region.amazonaws.com/dev/
Now if I try to reach the endpoint that redirect without the '/dev' path (/jump), I will get forbidden because is trying to reach https://my-api.some-region.amazonaws.com/api/info.
The one that set the path explicitly (/explicit-jump) works fine.
Fixing this single case is easy but I'm in the context of using an external app boilerplate (shopify express app) that has an incredible amount of redirects, really a high number.
I tried using a middleware that rewrites the urls when redirects:
app.use((req, res, next) => {
const redirector = res.redirect
res.redirect = function (url) {
console.log('CHANGING: ' + url);
url = url.replace('/api', '/dev/api')
console.log('TO: ' + url);
redirector.call(this, url)
}
next()
})
But I have the feeling that this is a brute force idea and actually it worked only in some occasions, somehow there are still redirects that goes to the base url ignoring the '/dev' path.
Is there a way I could fix this in a reasonable way so all redirects use the host in where the function is running?
I need to send list of apps after login to ejs template engine from server with expressjs. For that purpose, I am using res.render(). Even though it renders the specified file, it does not change the url. What should I do to redirect along with data and make changes to url.
routes.js
const loginUser = requie('../Controller/LoginController');
router.post('/login', loginUser);
LoginController.js
const loginUser = (req, res) => {
/* login code */
res.render('apps/app-list', {
title: 'Application List',
isLoggedIn: true
});
};
After successfull login, it is rendering the contents of apps/app-list, but url is still users/login.
If you are trying to send data you should render a page, here is an example from a piece of my app:
app.get("/myfood", ensureAuthenticated, (req, res) => {
Food.find({}, (error, allfood) => {
if(error) {
console.log(error)
} else {
res.render("myfood", {food: allfood})
}
})
})
So I am sending all found food items with the get request. And you can send multiple objects. Just separate them with a comma.
As I said in a comment you can't do the same if you want to
res.redirect()
So, in my app, I wanted to send a flash message when the user signs up. Here:
newUser.save()
.then(user => {
req.flash("sucess_msg", "Thank you for registering.")
res.redirect("/login");
})
You can search a bit on YouTube on how to use req.flash() there are a couple great tutorials. I learned about it from Brad Traversy, passport node app.
That's about all I can give you. req.flash() is defined in a global variable
app.use((req, res, next) => {
res.locals.sucess_msg = req.flash("sucess_msg");
res.locals.error_msg = req.flash("error_msg");
res.locals.error = req.flash("error");
next();
});
Try to do the same and maybe go from there. Hope you will be a step closer
I have an Express app that signs the user into Google using passport-google-oauth20, with the callback route: https://(hosturl)/auth/google/redirect.
I am trying to use this route to call my app after logging in using a ASWebAuthenticationSession and then get it to dismiss itself. I have already set my URL scheme in info.plist.
So far I have tried
api.get('/google/redirect', passport.authenticate('google'), (req, res) => {
res.status(301).redirect('com.googleusercontent.apps.<client id>');
});
which sends me to https://(hosturl)/auth/google/redirect/com.googleusercontent.apps.<client id>,
and
api.get('/google/redirect', passport.authenticate('google'), (req, res) => {
res.status(301).redirect('../../../com.googleusercontent.apps.<client id>');
});
which sends me to https://(hosturl)/com.googleusercontent.apps.<client id>
I have solved the issue, the redirect should be:
api.get('/google/redirect', passport.authenticate('google'), (req, res) => {
res.status(301).redirect('com.googleusercontent.apps.<client id>://');
});
The final '://' allows Express to recognise it as an external.
I'm trying to get the user data back from my database, but I can't seem to figure out how to send a query param to my server in order to do such a thing. My angular front end is running on a different port than my server (not sure that matters) but I can't figure it out.
I've tried using http.get to call the backend, but that doesn't seem to work.
This is the code in my auth.service:
reload() {
this.http.get('/user', {params: {userId: 'test'}});
}
This is the code on my server
app.get("/user/?userId", (req, res, next) => {
console.log('hello 2ddsaczczxczxC')
console.log(req);
})
My console logs aren't logging anything so it's clearly not reaching the backend at all.
Here is the change required for accessing any as such request parameters. Update your rest end point to
/user/:userid
app.get("/user/:userId", (req, res, next) => {
console.log('hello 2ddsaczczxczxC')
console.log(req.params);
})
Then access the query using either by request.params or req.query please check the documentation of expressjs as well.
You can try this:
app.get("/user/:userId", (req, res, next) => {
console.log();
}
You can pass query parameter by doing this
reload() {
this.http.get('/user', {queryParams: {userId: 'test'}});
}
I'm want to test the oauth2 (nodejs) in postman.
So, I made this route:
router.get('/authorise', (req, res, next) => {
console.log('in authorise');
});
Postman, I set this Url (which point to my route):
It's work. It gets to this route. but I am not able to find how to close this window and get the token?
What should the response look like?
I searched everywhere on the web and could not find any information about it.
I have try this but still not working:
router.get('/authorise', (req, res, next) => {
console.log('in authorise');
res.writeHead(302, {
Location: 'https://www.getpostman.com/oauth2/callback?access_token=8ba64c1fbe8d4c3a892e432425842adde38fbb0e&response_type=code'
});
res.end();
});
You need to open the window from the client side not from the Node application and when you receive the response from Node you can close the window.
I Found!
Just need to return AUTHORIZATION_CODE like so:
res.redirect(url.format({
pathname: "https://www.getpostman.com/oauth2/callback",
query: {
code: `AUTHORIZATION_CODE`
}
}));
Then is continue to Access Token Url.