Fetching from the root '/' route seems to not work? - node.js

I have a very simple server in expressjs from which I'll be getting some data, so far I just created basic routes and checked if they work, but I have an issue with the main '/' one. I added some extra routes for comparison
app.get('/', (req, res) => {
console.log('request at /');
})
app.get('/ree1', (req, res) => {
console.log('ree1');
})
app.get('/ree2', (req, res) => {
console.log('ree2')
})
app.get('/ree3', (req, res) => {
console.log('ree3')
})
Every time I fetch (from the browser console even) all the "/ree" routes log in the console, but the '/' one doesn't react at all. What could be the cause of that? Perhaps I missed something when I was learning basics.

Related

How to check the JWT token for specific routers

I have routers of type.
/auth/signIn
/auth/signUp
/user/all
/user/:id
/rooms/all
/rooms/:id
There is also a production route.
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, '../build', 'index.html'));
});
and I have function for verify JWTToken.
verifyJWTToken(req.headers.token)
.then((user) => {
req.user = user.data._doc;
next();
})
.catch((err: any) => {
res.status(403).json({message: "Invalid token."});
});
How can I correctly check the token for certain routers?
Especially /user/ , /rooms/
but not for /auth/ and production route
I want to note that the number of routes can become larger over time.
You can use verifyJWTToken method as a middleware to verify token for specific routes.
For rooms API,
router.get('/rooms', verifyJWTToken, (req, res) => {
// some operation
});
For production, you can skip the middleware.
UPDATED
For two routes /rooms/all and /rooms/:id,
If you have two separate route, like
router.get('/rooms/all', (req, res) => {
// some operation
});
and
router.get('/rooms/:id', (req, res) => {
// some operation
});
Then, you have to use middleware on both routes.
But if your setup is like,
app.use('/rooms', roomRoutes);
Now in your roomRoutes module, these two route exist,
router.get('/all', () => {});
router.get('/:id', () => {});
Then you can use only one middleware, like,
app.use('/rooms', verifyJwtToken, roomRoutes);

What are the best practices to work with next.js and express.js and use sessions

for a few weeks now i've started a project using node.js and express.js, I've also added React objects in the front.
I developped a full session manager using express-session and connect-mongodb-session and it works great.
I have one thing left to add now to have everything set up : next.js . And here it gets a little more complicated to me.
My purpose is to have the same thing I have now but with a smooth transition between pages.
I started using the official example from git : https://github.com/zeit/next.js/tree/canary/examples/custom-server-express
Which is very nice. But the pages in /page are public ? Someone could access them by entering their adress, which is not very good because sessions should be completly waterproof.
My first solution is to call them random names so people can't access them directly, but it's not very neat ... And they could still workarround ... This would make me write somehing like this :
server.get('/nice_name', (req, res) => {
console.log('loaded') return app.render(req, res, '/uoiuouiorlos_ugly_random_name', req.query) })
My other solution is to make a route for their adress and call
(req,res,next) => next()
This could work but ... is it pretty ?
Another solution is to edit next.config.js and write :
module.exports = {
useFileSystemPublicRoutes: true,
}
it works great but then every page is loading like they would normally do ... So what would be the point ?
const express = require('express')
const next = require('next')
const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
console.log('page loaded')
app.prepare().then(() => {
const server = express()
server.get('/', (req, res) => {
console.log('loaded')
return app.render(req, res, '/1A', req.query)
})
server.get('/space2', (req, res) => {
console.log('loaded')
return app.render(req, res, '/2A', req.query)
})
server.get('*', (req, res) => {
return handle(req, res)
})
server.listen(port, err => {
if (err) throw err
console.log(`> Ready on http://localhost:${port}`)
})
})
I'm a beginner using next, thank you in advance for your help !
for now redirecting to a page named 404.js if people try to access the actual page works fine
express.get('/', (req, res) => {
return app.render(req, res, '/landing_page', req.query);
})
express.get('/landing_page', (req, res) => {
return app.render(req, res, '/404', req.query)
});

Express router regex issue

I am using express router in my project, I am facing following problem,
I have 2 routes as follows
router.get("/user/:id", (req, res) => {
console.log("---- ABCD ---");
});
router.get("/user/list", (req, res) => {
console.log("---- PQRS ---");
});
When i call, http://localhost:3000/user/list api, ABCD is printed in console instead of PQRS.
I know we can write regex in router to handle this situation. I tried with following code.
router.get("/user/:id(!list$)", (req, res) => {
console.log("----- ABCD ----");
}
After making this change, /user/:id api stop working. But /user/list api is working
Please let me know, If I am doing something wrong. Thanks!
The issue is not with regex but. Reorder your route definition so that the dynamic routes are at the bottom. See the code below
router.get("/user/list", (req, res) => {
console.log("---- PQRS ---");
});
router.get("/user/:id", (req, res) => {
console.log("---- ABCD ---");
});

How do I automatically return a 404 when a GET path doesn't exist?

I am using NodeJS, Express and Handlebars (template engine) to build a web application. Currently I'm trying to automatically redirect users whenever they enter an URL that does not exist (or whenever they might not have access to it).
The following returns the index page:
router.get('/', (req, res) => {
res.render('index/index');
});
But how do I make something like this:
router.get('/:ThisCouldBeAnything', (req, res) => {
res.render('errors/404');
});
The following example is from Github:
Say that I enter this URL:
https://github.com/thispagedoesnotexist
It automatically returns a 404. How do I implement this in my application?
Thanks in advance.
Use a middleware just after all route handlers to catch non existing routes:
app.get('/some/route', function (req, res) {
...
});
app.post('/some/other/route', function (req, res) {
...
});
...
// middleware to catch non-existing routes
app.use( function(req, res, next) {
// you can do what ever you want here
// for example rendering a page with '404 Not Found'
res.status(404)
res.render('error', { error: 'Not Found'});
});
After all your other routes you can add:
app.get('*', (req, res) => {
res.render('errors/404');
});
Alternately, you can use a middleware function after all your other middleware and routes.
app.use((req, res) => {
res.render('errors/404');
});
So you might end up with something that looks like:
//body-parser, cookie-parser, and other middleware etc up here
//routes
app.get('/route1', (req, res) => {
res.render('route1');
});
app.get('/route2', (req, res) => {
res.render('route2');
});
//404 handling as absolute last thing
//You can use middleware
app.use((req, res) => {
res.render('errors/404');
});
//Or a catch-all route
app.get('*', (req, res) => {
res.render('errors/404');
});
I see that you have express tagged. All you have to do is include a default handler that includes
res.status(404).render('404template')
For example
app.get('*', (req, res,next) => {
res.status(404).render('error.ejs')
});

Node/Express send static file on request

I'm really new to node/express and I'm trying to understand how sending static files work. I managed to serve my index file, but I cannot serve other files as response of a GET request.
app.use(express.static(path.join(__dirname, '/client/build')))
app.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname, '.', 'client/build/', 'index.html'))
res.end()
})
app.get('/portfolio', (req, res) => {
const person = req.query.name
var filePath = __dirname + '/client/build/' + person + '/' + 'index.html'
res.sendFile(filePath)
res.end()
})
I found similar questions but nothing seems to work.
The request I send is:
fetch(`portfolio?name=${who}`)
There's a few problems with your code. One of them is that you end the request before the file is even done sending and another problem is that you're not using the res.sendFile method properly.
try something like this:
app.get('/', (req, res) => {
const fileDirectory = path.resolve(__dirname, '.', 'client/build/');
res.sendFile('index.html', {root: fileDirectory}, (err) => {
res.end();
if (err) throw(err);
});
})
app.get('/portfolio', (req, res) => {
const person = req.query.name
const fileDirectory = __dirname + '/client/build/' + person + '/';
res.sendFile('index.html', {root: fileDirectory}, (err) => {
res.end();
if (err) throw(err);
});
})
I don't recommend throwing an error whenever you get one but it should at least give you an idea how you can get this to work.
I finally solved it by using this on the server:
app.use( express.static(path.join(__dirname, 'client/build/person1')))
app.use( express.static(path.join(__dirname, 'client/build/person2')))
and calling it in the view like this:
<a href='/person1'></a>
<a href='/person2'></a>
As it seems, express.static resolves the paths on its own, so you don't need to handle the request yourself to serve the static files.
If this is not a good solution please coment

Resources