Loopback + React Router - GET 404 Error

344 views
Skip to first unread message

Cesar Ho

unread,
Mar 30, 2017, 8:33:28 AM3/30/17
to LoopbackJS
I am using loopback server and configured the static files to /client folder to serve index.html.
In the index.html it include the reactJS with React Router to produce an single page application.
The landing page is working fine, however, when I click the link say /blog, the server return GET 404 Error.

How to setup loopback to always return the index page so that React Router can work well?

Thanks.

Francois Laforge

unread,
Mar 30, 2017, 11:17:06 AM3/30/17
to loopb...@googlegroups.com
The problem is that Loopback is routing the calls first and /blog is not a loopback end point.

What we did was create a midldeware that routes all 404 calls to the react router:

LoopbackUrlNotFoundCatch.js
'use strict';

const path = require('path');
module.exports = function() {
 return function loopbackUrlNotFoundCatch(req, res, next) {
   var newPath = path.normalize(__dirname + '/../../client/index.html');
   res.sendFile(newPath);
 };
};

put this file in the /server/middleware/ folder

add a link in the middleware.json file
"final": {
   "./middleware/LoopbackUrlNotFoundCatch": {}
 },

Cesar Ho

unread,
Mar 31, 2017, 10:17:52 PM3/31/17
to LoopbackJS
Thank Francois,

Thanks for your solution. I the middleware.json, there is a urlNotFound parameter. Could we do anything on this parm?

  "final": {
    "loopback#urlNotFound": {}
  },

Thanks,
Cesar

Francois Laforge

unread,
Apr 3, 2017, 9:06:16 AM4/3/17
to loopb...@googlegroups.com
Huh,  I never noticed that.  Why, I bet there IS something you can do with that (but what exactly, I'm not sure).  Thanks for that.  I'm adding at task to our backlog to revisit our UrlNotFound code.  Thanks for the info!

Update

Just looked through the code.  We decided to replace the UrlNotFound middleware because I don't think it was working for us.  It would return a 404, but not give us the bad URL, so impossible to route to the react app.  Unfortunately the comments in the code are not very clear so I'm not 100% sure WHY we decided to abandon the UrlNotFound middleware.
Reply all
Reply to author
Forward
0 new messages