express API / react issue with routing - node.js

I have a problem where the appropriate routes are not being used in my React front end / express server API app.
Fetch requests from react work as they should, as do requests from Postman.
My problem is: when accessing the api routes from the browser, the react app is always sent.
Routes
GET /api/new
Takes one param url ie http://www.youtube.com
Sample request:
api/new?url=http://www.youtube.com
Response
e.g.
{short_link: http://localhost:8080/api/150} (150 being a unique ID.)
GET /api/:id
Takes one param id A unique number, e.g. 150
Sample request:
api/150
Response
Looks up id in DB, finds the short link
res.redirect(http://www.youtube.com)
Heres my repo
// server/index.js
const routes = require('./routes/index');
app.use('/', routes);
// server/routes/index.js
router.use(express.static(path.resolve(__dirname, '../../client/build')));
router.use('/api/new', catchErrors(link.setLink))
router.use('/api/:id', catchErrors(link.getLink))
router.use('/api/', catchErrors(index))
// All remaining requests return the front end
router.use('/', function(request, response) {
response.sendFile(path.resolve(__dirname, '../../client/build', 'index.html'));
});

Your issue is the same as this question where your express routes are conflicting.
You're telling your application to serve static content as your first route. I believe express routes are filtered through in the order that they're created, therefore I expect you're getting the top line executing and then the request completing instead of filtering down into the /api endpoints you want.
You should try moving your top line underneath your router.use('/api'...); code. This should attach your static assets after the API endpoints and I think this should fix the issue.

I cracked it! 🎉
My problem was that I had this line of code in my main app file:
// server/index.js
app.use('/', routes);
Which I thought would just direct it to my routes file:
// server/routes/index.js
router.use(express.static(path.resolve(__dirname, '../../client/build')));
router.use('/api/new', catchErrors(link.setLink))
router.use('/api/:id', catchErrors(link.getLink))
router.use('/api/', catchErrors(index))
// All remaining requests return the front end
router.use('/', function(request, response) {
response.sendFile(path.resolve(__dirname, '../../client/build', 'index.html'));
});
Fixed by changing:
// server/index.js
app.use('/', routes);
to
// server/index.js
app.use(routes);
The routes werent working because / + /api/ isnt a valid route!
Any further clarification on this much appreciated in my learning. 🤓

Related

How to use single piece of middleware with more than one express router?

I am working on a university project and we have decided to go for MEAN technology stack. To be honest I am a beginner with NodeJS and express, more precisely this is the first time I do sth with it.
I've found that is preferable to use express.Router rather than putting all routes to express instance e.g. app.post('path', function(req, res) { ... })
So this is what I have
var express = require('express');
var app = express();
function authorizationMiddleware(req, res, next) {
...
}
// handles login, doesn't meed autorizationMiddleware
var authRouter = express.Router();
authRouter.route('/login')
.post(function (req, res) {
...
});
// handles fetching of a single, all person(s), fetching of transactions for a person
var personRouter = require('./routes/personRoutes')(Person, Transaction, autorizationMiddleware);
//handles adding of a new transaction e.g. POST /api/transactions where params such as sender, recipient and amount are passed in body
var transactionRouther = require('./routes/transactionRoutes')(Person, Transaction, autorizationMiddleware);
app.use('/api', authRouter);
app.use('/api/persons', personRouter);
app.use('/api/transactions', transactionRoutes);
app.listen(8080, function () {
console.log('Listening on port: ' + 8080);
});
As you can see I have three routers (not even sure if I have gonne too far with them), authRouter is handling login only and I have also decided to separate persons logic from transactions logic too. (maybe I could have handled creation of new transaction in a way like /api/persons/:personId/transactions but I rather liked the idea of sending all required params in body).
I would like to ask if you agree with the solution I tried. As you can see I am passing authrizationMiddleware function (handles verification of JWT token) function to router modules and using it there.
Is there maybe a better way to use the same middleware with of multiple routers or is this a legit way?
Thx in advance
Cheers!
I don't get why you use 3 Routers. The "common" way to go (or at least the way I go) is to put all the routes in the same place, except when the path is very different or the purpose is different (for example I separate the error routes from the others).
For example, let's say I need to build a rest api for an app, I would probably have paths like:
/users/:userid
/users/:userid/comments/:commentid
/locations
...
All these routes can go in the same Router and if you want, you can apply specific authentication/authorization middlewares to them:
router.get("/users/:userid",
doAuthentication, authorizeOnUserId,
userController.getUserById);
router.get("/locations",
doAuthentication, authorizeLocations,
locationController.getAllLocations);
The middlewares are called in sequence and the request is passed on to the next middleware only if there are no errors (unauthenticaed/ unhauthorized).
Then you can simply import your routes like this:
app.use('/api', router);
Using this technique allows you to have a fine grain control over your routes.
Hope this helps.

How Express recorgonizes middlewares?

I'm novice in Express and a little bit confused about how it handles middlewares? So basically I have two middlewares which looks like:
app.use(require('_/app/middlewares/errors/404'))
app.use(require('_/app/middlewares/errors/500'))
404
var log = require('_/log')
module.exports = function (req, res, next) {
log.warn('page not found', req.url)
res.status(404).render('errors/404')
}
500
var log = require('_/log')
module.exports = function (er, req, res, next) {
log.error(er.message)
res.locals.error = er
res.status(500).render('errors/500')
}
So now I want to add my custom middleware app.use(require('_/app/middleware/shareLocals')) which looks like:
module.exports = function (req, res, next) {
res.locals.base_url = req.protocol + '://' + req.get('host');
next();
}
The main problem is that now when I try to use base_url I get 404 error...
So how Express understands what middleware do? That is between my middleware and 404 are no visual differences:
it receives same params
it doesn’t have any if's in it, just throws 404 error
Appears the feeling the middlewares in Express are made for errors (when excepts err as first param) and for 404 (when there is no first err)...
P.S.
Is there any difference defining middlewares before or after routes?
P.S. Is there any difference defining middlewares before or after routes?
Yes.
The order in which you register your middlewares (and routes) have a lot to say.
Image express as a giant list. Starting at the first element in the list, you have the first middleware OR route you have defined, next is the second, etc.
When express gets a request, it appears to be matching your route/name of route/middleware, and if it's a hit, it executes the middleware/route and potentially waits for a "next()" call.
So if you have a route "/test" it will only be executed if you have a request matching "/test". routes with different names obviously wont get triggered. middlewares can also have names: app.use("/test", middlewareA). This will also only trigger if "/test" is requested. The way you do it, all requests (within the routes namespace) will be triggered app.use(middlewareA). It's like a wildcard.
Now, to the implications of things being ordered:
Your 404 middleware should only be used AFTER all routes have been defined. that way, when the list reached the 404 middleware, no routes have actually been found.
returning/sending result/not calling next() at the end of a middleware will all potentially create problems in your flow. I wont go into details about this, but be aware of it.
I am guessing your own middleware is added after the 404 middleware. That is probably the problem. If not, you should surrender more of your code so we can take a better look. But remember, order is everything :)

ExpressJS Applying middleware only to routes in router

I have app where I have public routes and authorized routes. Public routes should go through auth as well, but if auth fails, it doesn't matter.
So I have two routers:
var publicRoutes = express.Router();
var secretRoutes = express.Router();
publicRoutes
.use(auth)
.use(ignoreAuthError);
publicRoutes.get('/public', function(req, res){
res.status(200).send({message: "public"});
});
secretRoutes
.use(auth)
.use(handleAuthError);
secretRoutes.get('/secret', function(req, res){
res.status(200).send({message: "secret"});
});
...
app.use(publicRoutes);
app.use(secretRoutes);
Now everything works fine, but if I change the order of app.use public routes throw auth error. Also I cannot get any 404, 500 etc errors, because they all go through auth errors.
So obviously what is happening is that Router.use() is being applied to all routes with the same root - in this case "/"
Therefore I think if I would use just auth middleware on all routes and then add other middlewares directly to routes it should work fine. But it kind of brakes the point of having multiple Routers for me.
I would expect that if I use Router.use() the middleware will apply only if that particular router matches any routes it has set up, instead of changing behavior of other router.
Do I understand this correctly? Is there any way to handle this without actually having to add middleware to every single route?
Had the same issue, solved thanks to #Explosion Pills comment.
Bad:
app.use(secretRoutes); // router.use calls won't be scoped to "/secret"
app.use(publicRoutes); // public routes will be impacted
Good:
app.use("/secret", secretRoutes); // router.use calls will be scoped to "/secret"
app.use("/public", publicRoutes); // public routes won't be impacted

404 when accessing new route

I'm trying to add a new route (/profile) to my NodeJS Express web application. I've modified my app.js file like this:
var routes = require('./routes/index');
var profile = require('./routes/profile');
app.use('/', routes);
app.use('/profile', profile);
The '/' index path works fine, my issue is with '/profile'. Whenever I try to access it, I get a 404. This is profile.js:
var express = require('express');
var router = express.Router();
router.get('/profile', function(req, res) {
var username = req.session.username;
if(username) {
res.render('profile');
} else {
res.redirect('/login');
}
});
module.exports = router;
I don't understand what I'm doing wrong because in the example express application that is generated, '/users' works fine. I basically copied that format, but it's throwing a 404. Any ideas?
In my profile.js, I had to change my GET request path to this:
router.get('/', function(req, res) {
//code
});
Otherwise, the router would be looking for /profile/profile. When I change it to /, it's just looking for the root of `/profile', or at least that's how I understand it.
To understand what you are doing wrong you should know that Node.js uses middleware functions to route your requests. To simplify you can think about it as a chain of functions.
Middleware is like a plumbing pipe, requests start at the first middleware you define and work their way “down” the middleware stack processing for each path they match.
So with the following statement you added a middleware function to handle any request starting with the root path /profile, and it is a common pattern in Node to use the use method to define the root paths.
app.use('/profile', profile);
The use method is doing part of the routing in your scenario and the statement above will match any route starting with that path, including /profile/all or /profile/12 or even /profile/go/deeper/inside.
However, you want to narrow down that routing to something more specific, so that is why you pass a router middleware function (profile in your case) to match more specific routes instead of all routes starting with /profile.
The profile middleware function is actually the next step in the chain of functions to execute, and it will start from the root path specified in the use statement, which is the reason why you need to start again with / and not with /profile. If you wanted to match a profile by ID you would do:
router.get('/:id', ...)
Which would be concatenated with the base URL (from the /use statement) and would match a request like /profile/2 or /profile/abc.

Node Express auth status

I have multiple routes, split into different files (my app consists of different "modules", which I maintain in separate folders. For each folder, there is an index.js file in which I manage the routes per module, and I require these in the app.js file).
For every route, I will require to check the auth, and pass the loggedIn status to the header of every page:
//Default variables for the ejs template
var options = {
loggedIn: true
};
res.render("home/home", options);
If the logged in status is true, then the user's name will be displayed. If not, the login / signup labels are displayed.
What is the best way to centralise this, so that I don't need to require the auth script in every of these index.js (route) files?
I need to be able to pass the auth status to the view via the options object (see example).
In your auth, module, use a middleware function. That function can check and store res.locals.loggedIn which will be available for any view that will eventually be rendered. Just make sure the app.use call executes prior to your other routes and it will work properly.
app.use(function auth(req, res, next) {
res.locals.loggedIn = true; // compute proper value here
next();
});
From what I understand you need to do this for every request.One common thing is adding this as middleware so that all the request gets this .
For Example :
var http = require('http');
var connect = require('connect');
var app = connect();
app.use(function(req, res) {
res.end('Hello!');
});
http.createServer(app).listen(3000)
Now for every request , Hello is printed . You could extract this as a module and reuse it across projects. Check here for more details

Resources