使用angular.js和express表示路由错误

Dan*_*ang 4 javascript express angularjs

我正在尝试使用angular.js在/ parent root周围进行路由,如果我正在使用锚链接等工作(也就是路由纯粹从angular处理.例如,一个href为'/ parent/createstudent'的链接有效但是,当我在url栏中输入它或者当它已经在该位置时刷新它时,它会生成错误,因为后端路由尚未完成.

因此我在express中尝试了一个catchall路由('/ parent/*'),但这导致了我的所有js和css都没有被读取的错误.有谁知道如何解决这个问题?

我的静态文件目录

public
  -> javascripts
      -> app.js
      -> angular.js
  -> stylesheets
  -> images
Run Code Online (Sandbox Code Playgroud)

错误:

Resource interpreted as Script but transferred with MIME type text/html: "http://localhost:3000/parent/javascripts/jquery.js". home:1
Resource interpreted as Script but transferred with MIME type text/html: "http://localhost:3000/parent/javascripts/angular.js". home:1
Resource interpreted as Script but transferred with MIME type text/html: "http://localhost:3000/parent/javascripts/main.js". home:1
Uncaught SyntaxError: Unexpected token < jquery.js:1
Uncaught SyntaxError: Unexpected token < angular.js:1
Uncaught SyntaxError: Unexpected token < 
Run Code Online (Sandbox Code Playgroud)

表达

app.get('/parent', function(req, res) {
  res.render('main')
});
app.get('/parent/*', function(req, res) {
  res.render('main')
});
Run Code Online (Sandbox Code Playgroud)

角度路由(我在视图中声明控制器)

var app = angular.module('app', []).config(function($routeProvider, $locationProvider) {
  $locationProvider.html5Mode(true);
  $routeProvider.when('/parent/login', 
    {
      templateUrl: '../templates/login.html'
    }).
    when('/parent/home', 
    {
      templateUrl: '../templates/home.html'
    }).
    otherwise(
    {
      redirectTo: '/parent'
    })
})
Run Code Online (Sandbox Code Playgroud)

Ven*_*Ven 16

这是一个新引入的"行为改变"(或bug).

尝试使用基本标记:

<base href="/" />
Run Code Online (Sandbox Code Playgroud)

  • @kontur,在这里你去:https://docs.angularjs.org/error/$location/nobase (2认同)

rob*_*lep 6

您也可以通过以下方式/parent为JS/CSS服务:

... http://localhost:3000/parent/javascripts/jquery.js
                         ^^^^^^^
Run Code Online (Sandbox Code Playgroud)

因此,如果声明express.static中间件之前声明路由,则catch-all路由将处理所有JS/CSS请求.

您应该使用类似于此的设置:

// express.static() first...
app.use('/parent', express.static(__dirname + '/public'));

// ...followed by your catch-all route (only one needed)
app.get('/parent*', function(req, res) {
  res.render('main')
});
Run Code Online (Sandbox Code Playgroud)