AngularJS $ routeProvider templateUrl always returns 404 using Express

So the problem is that AngularJS $routeProvider/ngRoute does not work the way I need. I cannot get it to display the corresponding .html page on my route. I always get GET http://localhost:3000/home.html 404 (Not Found) when I try to load a template on the index.ejs page.

I tried many path options to download .html , but I was not successful. I even created home.html for each folder in the application to see if anything is enough, but nothing works. ng-include does not work with direct embedding in html.

/app.js simplified: the source code uses express.router()

 var express = require('express'); var app = express(); var path = require('path'); var ejs = require('ejs'); app.set('view engine', 'ejs'); app.set('views', path.join(__dirname, 'views')); app.use(express.static(path.join(__dirname, 'public'))); app.get('/', function(req,res,next) { res.render('index', { page: 'index' }); }); app.listen(3000,function(){ console.log('3k'); }); 

/views/index.ejs

 <!DOCTYPE html> <html lang="en" ng-app="App"> <head> <meta charset="UTF-8"> <title>WHY???</title> </head> <body> <div class="main"> <div ng-view></div> </div> <script src="/vendor/angular/angular.js"></script> <script src="/vendor/angular-route/angular-route.js"></script> <script src="/angular/angularApp.js"></script> </body> </html> 

/state/angular/angularApp.js

 var App = angular.module('App',['ngRoute']); App.config(['$routeProvider', function($routeProvider) { $routeProvider .when('/', { templateUrl: 'views/index/home.html' }) .when('/team', { templateUrl: '/views/index/team.html' }) .when('/faq', { templateUrl: '/views/index/faq.html' }) .otherwise({ redirectTo: '/' }) }]); 

home.html, team.html, and faq.html all have simple lines of code for testing purposes. Example: <h1> This is home.html </h1>

Folder structure

 app.js public/ |-vendor/ |-angular/ | |-angularApp.js views/ |-index.ejs | |-index/ | |-home.html | |-faq.html | |-team.html 
+5
source share
1 answer

Node / Express serves everything statically from a "public" folder. You need to set all your URLs relative to the public directory. Your index folder should be moved to the public.

 app.js public/ |-vendor/ |-angular/ | |-angularApp.js |views/ | |-index/ | | |-home.html | | |-faq.html | | |-team.html views/ |-index.ejs 

This folder structure should work. Also fix this:

  when('/', { templateUrl: '/views/index/home.html' }) 
+4
source

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


All Articles