Corner and Express Routing 404

I have the following AngularJS application:

angular.module('app', ['ngRoute', 'app.controllers']) .config(['$routeProvider', function($routeProvider){ $routeProvider .when('/', { controller: 'HomeController', templateUrl: 'views/home.html' }) .when('/garage', { controller: 'GarageController', templateUrl: 'views/vehicle.html' }) .otherwise({ redirectTo: '/' }); }]) .config(['$locationProvider', function($locationProvider) { $locationProvider.html5Mode(true); }]); 

Node.js is my backend, and its sole purpose is to provide a REST api (which is not yet implemented). Express configuration is as follows:

 app.use(express.static(path.join(__dirname, 'public'))); app.get('*', function(req, res) { res.sendFile(__dirname + '/public/index.html'); }); 

The problem is that whenever I put some invalid URL in the address bar, for example, the request http://localhost:3000/abc reaches the server. I suggested that it should be handled by AngularJS routing and redirected to the default "/" page. Why is this not happening? When this happens, all applications are loaded again, all index and asset files. I would like to say that AngularJS - whenever someone enters the wrong route, just go to the standard ones. And that should just replace ng-view, and not load the entire index.html again. Is it possible?

thanks

+5
source share
2 answers

Not sure if this helps, but this routing works very well. (App.js)

 var routes = require('./routes/index'); var users = require('./routes/users'); var api = require('./routes/api') var partials = require('./routes/partials') 

Then, on the other end, the following code to get angular routes the launch:

  var BabyPadz = angular.module('BabyPadz', ["ngResource", "ngRoute"]). config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) { $locationProvider.html5Mode(true); $routeProvider .when('/', { templateUrl: 'partials/index', controller: 'IndexController' }) .when('/about', { templateUrl: '/partials/about', controller: 'AboutController' }) .when('/contactus', { templateUrl: "partials/contactus", controller: 'ContactController' }) .when('/boompad', { templateUrl: "partials/boompad", controller: "BoomController" }) // route for the about page .otherwise({redirectTo: "/test"}); } ] ); 

I realized that I am using ngResource, I know that something has changed a year or two ago, something about the split angular (so Route, etc. is a separate module). Not sure if this is so.

I still get 404 times, but I think this is the end of the server to allow angular to collect routing, but could not fully answer this question, how routing (server / angular) works together or what gets priority.

0
source

I had the same problem you encountered and you have 2 possible solutions!

//////////////////////////////

Solution # 1: List of directories that you make / donโ€™t want to โ€œserviceโ€

//////////////////////////////

How to do:

Let's say your directory structure looks like this:

 -app/ ---controllers/ ---directives/ ---etc. -public/ ---img/ ---css/ ---index.html ---etc. -views/ ---home.html ---vehicle.html ---etc. -app.js (run with 'node app.js') 

Some of these 3 folders (applications, public, views) have different rules according to which you want to serve and which you want to display:

  • Appendix /
    • serve: If your site does GET / app / controller.js, you want to serve them in a literal file.
  • public /
    • serve: If your site does GET / public / img / logo.jpg, you want to serve them with a literal file.
  • view /
    • render: If your site does GET views / home, you want to display their view from your angular.js route.

Now, from your node / express js file, find or add the following:

 //This tells node that these folders are for STATIC SERVING files (meaning literal files). //And Yes! You can use multiple to indicate multiple directories. app.use(express.static(path.join(__dirname, 'app'))); app.use(express.static(path.join(__dirname, 'public'))); 

Additional Information:

app.use(express.static(__dirname + '/client/views')); means that you are serving literal files from / client / views, but nothing from this directory. See angularjs index.html in the views folder

Extended example:

This will be your possible configuration:

 //app.js var express = require('express'), bodyParser = require('body-parser'), methodOverride = require('method-override'), errorHandler = require('error-handler'), morgan = require('morgan'), routes = require('./routes/index'), //My special routes file http = require('http'), path = require('path'); var app = module.exports = express(); // all environments app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(morgan('dev')); app.use(bodyParser()); app.use(methodOverride()); app.use(express.static(path.join(__dirname, 'app'))); app.use(express.static(path.join(__dirname, 'public'))); // serve index and view partials app.get('/', routes.index); //Partials app.get('/partials/:name', routes.partials); // redirect all others to the index // BUT the static files listed above still get served statically app.get('*', routes.index); http.createServer(app).listen(app.get('port'), function () { console.log('Express server listening on port ' + app.get('port')); }); 

Then this will be your routes file:

 exports.index = function(req, res){ res.render('index'); }; exports.partials = function (req, res) { var name = req.params.name; res.render('partials/' + name); }; 

//////////////////////////////

Solution # 2: check if the file exists first

//////////////////////////////

How to do:

Keep everything as you already have, but instead of trying "res.sendFile" right away, check if it exists first. For instance:

 exports.all = function (req, res) { var name = req.params[0]; fs.exists(path+'/'+name, function(exists){ if(exists) { //console.log("file exists"); res.sendFile(path+'/'+name); }else{ //console.log("file does not exist"); //redirects to index res.render('index'); } }); }; 

Extended example:

This will be your possible configuration:

 //app.js var express = require('express'), bodyParser = require('body-parser'), methodOverride = require('method-override'), errorHandler = require('error-handler'), morgan = require('morgan'), routes = require('./routes/index'), //My special routes file http = require('http'), path = require('path'); var app = module.exports = express(); // all environments app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(morgan('dev')); app.use(bodyParser()); app.use(methodOverride()); app.use(express.static(path.join(__dirname, ''))); // serve index and view partials app.get('/', routes.index); //Partials app.get('/partials/:name', routes.partials); // redirect all others app.get('*', routes.all); http.createServer(app).listen(app.get('port'), function () { console.log('Express server listening on port ' + app.get('port')); }); 

and this is your routes file:

 var fs = require('fs'); var path = require('path'); exports.index = function(req, res){ res.render('index'); }; exports.partials = function (req, res) { var name = req.params.name; res.render('partials/' + name); }; exports.all = function (req, res) { var name = req.params[0]; fs.exists(path+'/'+name, function(exists){ if(exists) { //console.log("file exists"); res.sendFile(path+'/'+name); }else{ //console.log("file does not exist"); //redirects to index res.render('index'); } }); }; 

//////////////////////////////

Hope this helps!

0
source

Source: https://habr.com/ru/post/1206830/


All Articles