How to configure frontend routes with AngularJS and an ExpressJS server?

0

Good morning,

I am currently setting up a SPA application, where I want to manage all the routes with AngularJS and that the Express routes are only for API, the problem I have is that if I configure the Angular routes for example:

http://localhost:3001/login

For angular with a redirection I get it, but if I'm standing on that route and surcharge (F5) the server says that there is no such route, and it is clear because there is no such route in the configuration of express routes, now my doubt is how do I configure it so that angular is the one that handles all routes? and even if I give F5 in a view can continue in it, is there any way to configure express for the route to handle them? the frontend and the backend only handle the routes for requests, that is to be clearly like API REST.

First of all thank you very much in advance.

Greetings.

    
asked by Carlos Aguilera 18.04.2017 в 18:38
source

2 answers

0

In a SPA application, routes are handled on the client, not on the server. If you do a recharge or type directly in the address bar, what will happen, obviously, is that a request GET will be made to the server, returning a 404.

The routes for the API must go first, then redirect any incoming requests to the index.html of your application:

API router

const router = express.Router();
router
  .get('/users', UserController.index)
  ...

export default router;

App

app.use(express.static(join(__dirname, 'public')));
app.use('/api', apiRoutes);

app.get('*', (req, res) => {
  res.type('html');
  res.sendFile(RUTA_A_index.html);
});

Now when you reload the page, the index.html will be sent as an answer and AngularJS will be responsible for rendering the correct view according to the URL.

    
answered by 18.04.2017 / 19:23
source
0
Proyecto
|_server.js
|_public
  |_app
    |_index.hmtl
    |_module.js
    |_funcionalidad-1
      |_ruute.js
      |_module.js
      |_funcionalidad.css
      |_funcionalidad.hmlt
    |_funcionalidad-2
    :
  |_assent
|_package.json
|_bower.json
|_gulp.js

Where do I place the backend part of the routes and all the functionalities? I also have a problem that when I enter the server in the path http://localhost:3001/ I can not see anything, but if I access http://localhost:3001/app/ if it works, I do not understand very well because that happens.

If you could help me in that, I would greatly appreciate it.

Thank you very much.

    
answered by 19.04.2017 в 00:48