当在浏览器中直接访问 URL 时,Angular 路由不起作用,但在单击时起作用? [英] Angular routing doesn't work when URL is directly visited in browser but works when clicked to?

查看:25
本文介绍了当在浏览器中直接访问 URL 时,Angular 路由不起作用,但在单击时起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有目录结构的角度应用

I have an angular app with a directory structure

app 
..views
....partials
......main.jade
......foo.jade
....index.jade

和路由定义如下:

'使用严格';

angular.module('myApp', [
  'ngCookies',
  'ngResource',
  'ngSanitize',
  'ngRoute', 
  'firebase', 
  'myApp.config'
])
  .config(function ($routeProvider, $locationProvider) {
    $locationProvider.html5Mode(true);  

    $routeProvider
      .when('/', {
        templateUrl: '/partials/main',
        controller: 'MainCtrl'
      })
      .when('/foo/:fooName', {
        templateUrl: '/partials/foo',
        controller: 'FooCtrl'
      })            
      .otherwise({
        redirectTo: '/'
      });
  });

我在服务器端使用express,相关代码是:

I'm using express on the server side and the relevant code is:

    // server.js 
   app.configure('development', function(){
     app.use(express.static(path.join(__dirname, '.tmp')));
     app.use(express.static(path.join(__dirname, 'app')));
     app.use(express.errorHandler());
   });

   app.configure('production', function(){
    app.use(express.favicon(path.join(__dirname, 'public/favicon.ico')));
    app.use(express.static(path.join(__dirname, 'public')));
   });

    app.get('/', routes.index);
    app.get('/partials/:name', routes.partials);

    //routes.js
    exports.index = function(req, res){
      res.render('index');
    };


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

主要路线 "/" 加载良好,当我点击 "/foo/bar" 部分视图 foo.jade 加载正如预期的那样.但是,当我尝试直接在 URL 中访问 "/foo/bar" 时,我收到来自 Express "cannot GET/foo/bar" 的 404 响应,这是有道理的,因为有没有像这样的路线在快递中定义.但是,我认为这是定义角度路由器的重点..i.e.它应该拦截这个请求并实际请求 "/partials/foo".我尝试添加

The main route "/" loads fine and when i click to "/foo/bar" the partial view foo.jade loads as expected. However, when I try visiting "/foo/bar" directly in the URL i get a 404 response from Express "cannot GET /foo/bar" which makes sense since there's no route like this defined in express. However, I thought this was the whole point of defining the angular router..i.e. it's supposed to intercept this request and actually ask for "/partials/foo". I tried adding

//redirect all others to the index (HTML5 history)
app.get('*', routes.index);

但它没有解决问题,似乎甚至捕获了对静态 js 资产的请求,并以 index.html 的内容进行响应,这非常糟糕.我确定我做错了什么.如何解决问题以便我可以直接访问 URL?

but it didnt solve the issue and seemed to be catching even the requests for static js assets and responding with the contents of index.html which is pretty bad. I'm sure I'm doing something wrong. How can I fix things so that I can directly visit the URLs?

推荐答案

路由出现这种情况的原因是打开了 html5mode.注意这一行:$locationProvider.html5Mode(true);

The reason routing is behaving like this is html5mode turned on. Notice the line: $locationProvider.html5Mode(true);

您需要了解,当您尝试直接访问 "/foo/bar" 时,您的浏览器会向此 URL 发送 HTTP GET 请求.当您尝试通过点击链接访问此 url 时,如您所说,Angular 会拦截此操作并调用仅更新浏览器链接的 History.pushState.

You need to understand that when you try to access "/foo/bar" directly your browser sends HTTP GET request to this URL. When you try to access this url via link clicking, like you said, Angular is intercepting this action and calls History.pushState that only updates browser's link.

为了使 html5mode 路由工作,您需要做的是实现 url 重写.每个请求都必须重定向到引导 AngularJS 应用程序的索引文件,但这需要在您的服务器上完成.Angular 将自行呈现所需的页面.

What you need to do in order to make html5mode routing work is implementing url rewrite. Every request has to be redirected to your index file that bootstraps AngularJS application, but this needs to be done on your server. Angular will render the desired page by itself.

查看connect mod rewrite grunt 任务,它就是这样做的.

Check out connect mod rewrite grunt task that does exacly that.

你也可以直接这个中间件.

这篇关于当在浏览器中直接访问 URL 时,Angular 路由不起作用,但在单击时起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆