AngularJS - html5Mode - 不能得到/登录 [英] AngularJS - html5Mode - Cannot GET /login

查看:161
本文介绍了AngularJS - html5Mode - 不能得到/登录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

喜已经创建了自耕农,咕噜和亭子1 angularJS应用。
我已启用应用程序的html5Mode。而其工作。但是,当我刷新页面(本地主机:9000 /登录),它说:

Hi have created one angularJS application with yeoman, grunt and bower. I have enabled the html5Mode for the application. And its working. But, when I refresh a page (localhost:9000/login), it says

Cannot GET /login //or any url I type or refresh

下面是应用程序的结构。

Here is application structure

MainApp
|
|__app
|  |
|  |__bower_components
|  |
|  |__scripts
|  | |
|  | |__ app.js
|  | |
|  | |__contollers -- login.js, home.js, register.js
|  | |
|  | |__service -- js files
|  | |
|  | |__styles -- CSS files
|  | |
|  | |__views -- main.html, login.html, register.html,home.html
|  |
|  |__ index.html
|
|__ node_modules
|
|__ bower.json, Gruntfile.js, karma-conf.js, karma-e2e.conf.js, package.json

下面是我的 app.js 路由

'use strict';    
var superClientApp=angular.module('mainApp', ['ngCookies']);

//Define Routing for app
superClientApp.config(['$routeProvider', '$locationProvider',
  function($routeProvider,$locationProvider) {
    $routeProvider
    .when('/login', {
        templateUrl: 'login.html',
        controller: 'LoginController'
    })
    .when('/register', {
        templateUrl: 'register.html',
        controller: 'RegisterController'
      })
    .when('/home', {
       templateUrl: 'views/home.html',
       controller: 'homeController'
    })
    .otherwise({
       redirectTo: '/login'
    });
    $locationProvider.html5Mode(true);
}]);

下面是我Gruntfile.js的一部分

Here is my part of Gruntfile.js

'use strict';
var LIVERELOAD_PORT = 35729;
var lrSnippet = require('connect-livereload')({ port: LIVERELOAD_PORT });
var mountFolder = function (connect, dir) {
  return connect.static(require('path').resolve(dir));
};
var proxySnippet = require('grunt-connect-proxy/lib/utils').proxyRequest;

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'

module.exports = function (grunt) {
  require('load-grunt-tasks')(grunt);
  require('time-grunt')(grunt);

  // configurable paths
  var yeomanConfig = {
    app: 'app',
    dist: 'dist'
  };

  try {
    yeomanConfig.app = require('./bower.json').appPath || yeomanConfig.app;
  } catch (e) {}

  grunt.initConfig({
    yeoman: yeomanConfig,
    watch: {
      coffee: {
        files: ['<%= yeoman.app %>/scripts/{,*/}*.coffee'],
        tasks: ['coffee:dist']
      },
      coffeeTest: {
        files: ['test/spec/{,*/}*.coffee'],
        tasks: ['coffee:test']
      },
      styles: {
        files: ['<%= yeoman.app %>/styles/{,*/}*.css'],
        tasks: ['copy:styles', 'autoprefixer']
      },
      livereload: {
        options: {
          livereload: LIVERELOAD_PORT
        },
        files: [
          '<%= yeoman.app %>/{,*/}*.html',
          '.tmp/styles/{,*/}*.css',
          '{.tmp,<%= yeoman.app %>}/scripts/{,*/}*.js',
          '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
        ]
      }
    },
    autoprefixer: {
      options: ['last 1 version'],
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/styles/',
          src: '{,*/}*.css',
          dest: '.tmp/styles/'
        }]
      }
    },
    connect: {
      options: {
        port: 9000,
        // Change this to '0.0.0.0' to access the server from outside.
        hostname: 'localhost'
      },
      proxies: [
        {
            context: '/serverApp',
            host: 'localhost',
            port: '8080',
            https: false,
            changeOrigin: false
        }
      ],
      livereload: {
        options: {
          middleware: function (connect) {
            return [
              lrSnippet,
              proxySnippet,
              mountFolder(connect, '.tmp'),
              mountFolder(connect, yeomanConfig.app)
            ];
          }
        }
      },

我已经通过<一个了href=\"http://stackoverflow.com/questions/16569841/angularjs-html5-mode-reloading-the-page-gives-wrong-get-request\">this SO质疑。并根据接受的答案,我改变了我的Gruntfile.js下面。

I have gone through this SO question. And based on the accepted answer, I changed my Gruntfile.js to below.

'use strict';
var LIVERELOAD_PORT = 35729;
var lrSnippet = require('connect-livereload')({ port: LIVERELOAD_PORT });
var mountFolder = function (connect, dir) {
  return connect.static(require('path').resolve(dir));
};
var proxySnippet = require('grunt-connect-proxy/lib/utils').proxyRequest;

var urlRewrite = require('grunt-connect-rewrite');

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'

module.exports = function (grunt) {
  require('load-grunt-tasks')(grunt);
  require('time-grunt')(grunt);

  // configurable paths
  var yeomanConfig = {
    app: 'app',
    dist: 'dist'
  };

  try {
    yeomanConfig.app = require('./bower.json').appPath || yeomanConfig.app;
  } catch (e) {}

  grunt.initConfig({
    yeoman: yeomanConfig,
    watch: {
      coffee: {
        files: ['<%= yeoman.app %>/scripts/{,*/}*.coffee'],
        tasks: ['coffee:dist']
      },
      coffeeTest: {
        files: ['test/spec/{,*/}*.coffee'],
        tasks: ['coffee:test']
      },
      styles: {
        files: ['<%= yeoman.app %>/styles/{,*/}*.css'],
        tasks: ['copy:styles', 'autoprefixer']
      },
      livereload: {
        options: {
          livereload: LIVERELOAD_PORT
        },
        files: [
          '<%= yeoman.app %>/{,*/}*.html',
          '.tmp/styles/{,*/}*.css',
          '{.tmp,<%= yeoman.app %>}/scripts/{,*/}*.js',
          '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
        ]
      }
    },
    autoprefixer: {
      options: ['last 1 version'],
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/styles/',
          src: '{,*/}*.css',
          dest: '.tmp/styles/'
        }]
      }
    },
    connect: {
      options: {
        port: 9000,
        // Change this to '0.0.0.0' to access the server from outside.
        hostname: 'localhost',
        base: 'app',
        middleware: function(connect, options) {
            // Return array of whatever middlewares you want
            return [
              // redirect all urls to index.html in build folder
              urlRewrite('app', 'index.html'),

              // Serve static files.
              connect.static(options.base),

              // Make empty directories browsable.
              connect.directory(options.base)
            ];
          }
      },
      proxies: [
        {
            context: '/serverApp',
            host: 'localhost',
            port: '8080',
            https: false,
            changeOrigin: false
        }
      ],
      livereload: {
        options: {
          middleware: function (connect) {
            return [
              lrSnippet,
              proxySnippet,
              mountFolder(connect, '.tmp'),
              mountFolder(connect, yeomanConfig.app)
            ];
          }
        }
      },

不过还是我收到了同样的错误,当我刷新页面。如何解决此问题?

But still I am getting the same error when I refresh the page. How to solve this?

推荐答案

您必须有一个服务器端解决方案来重定向所有非解析流量的index.html

You must have a server side solution to redirect all non resolving traffic to index.html

我将分享这一个htaccess版本和Node.js的版本。我也曾在春季启动实施这一点,但是这是一个有点更多地参与。

I will share an htaccess version of this and a node.js version. I have also implemented this in spring-boot, but that was a little bit more involved.

的.htaccess

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /the-base-from-index.html/


    RewriteEngine on
    RewriteCond %{HTTP:X-Requested-With} !XMLHttpRequest$
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule . index.html [L]
</IfModule>

为了这个工作Apache配置必须启用了mod_rewrite,也允许覆盖所有。重写将在Apache的配置正常工作。

In order for this to work your apache config must have mod_rewrite enabled and also allow override all. The rewrite will work in apache config as well.

还有,让您在Ajax请求返回404的条件。为了这工作,你必须注册pre-飞行头到所有$ http请求表明它们是XMLHTTP请求。是这样的:

There is also a condition that allows you to return 404 on ajax request. In order for that to work you must register a pre-flight header to all $http request signifying that they are xmlhttp requests. something like:

 myapp.config(function($httpProvider) {
      $httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
 });

的NodeJS

var express = require('express');
var bodyParser = require('body-parser')
var path = require('path')
var app = express();

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

app.listen(9090);
console.log("Node Server Listening on port 9090");

这是污垢简单,并且可以改进。即以对REQ头检查的XMLHTTP头,类似于什么htaccess的例子做的。

This is dirt simple, and could be improved. Namely with a check on the req headers for the xmlhttp header, similarly to what the htaccess example is doing.

这些获得跨越的总体思路。基本上,这将导致404的流量都担任的index.html来代替。这使您可以继续提供静态内容,但你的路由(只要它们实际上并不在该位置的磁盘上存在)将返回的index.html。

These get the general idea across. Basically any traffic that would result in a 404 gets served index.html instead. This allows you to continue to serve up static content, but your routes (as long as they don't actually exist on the disk at that location) will return index.html.

警告!不喜欢在所有Ajax请求preflight头的解决方案,任何未解决的模板请求将导致一个无限循环,并有可能锁定浏览器。

Warning! without a solution like the preflight header on all ajax request, any unresolved template request will result in an infinite loop and likely lock up your browser.

这篇关于AngularJS - html5Mode - 不能得到/登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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