AngularJS – html5Mode – 无法GET /登录

前端之家收集整理的这篇文章主要介绍了AngularJS – html5Mode – 无法GET /登录前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
您已经创建了一个具有yeoman,grunt和bower的angularJS应用程序.
我已经为应用程序启用了 html5Mode.和它的工作.但是,当我刷新页面(localhost:9000 / login)时,它说
Cannot GET /login //or any url I type or refresh

这里是应用程序结构

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的一部分

'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/{,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: '{,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'),yeomanConfig.app)
            ];
          }
        }
      },

我已经经历了this SO question.根据accepted answer,我将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;

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

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,// 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)
            ];
          }
      },

但是当我刷新页面时,我仍然会遇到相同的错误.如何解决这个问题?

您必须具有服务器端解决方案,将所有非解析流量重定向到index.html

我将分享一个htaccess版本的这个和一个node.js版本.我也在spring-boot中实现了这一点,但是有一点更多的涉及.

.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配置中工作.

还有一个条件允许您在ajax请求上返回404.为了使其工作,您必须向所有$http请求注册一个预飞行头,表示它们是xmlhttp请求.就像是:

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");

这是污垢简单,可以改进.也就是通过检查xmlhttp头的req标头,类似于htaccess示例在做什么.

这些得到了一般的想法.基本上,导致404的任何流量将被转换为index.html.这允许您继续提供静态内容,但是您的路由(只要它们实际上不存在于该位置的磁盘上)将返回index.html.

警告!没有一个解决方案像所有ajax请求的预检标题,任何未解决的模板请求将导致无限循环,并可能锁定您的浏览器.

原文链接:https://www.f2er.com/angularjs/140491.html

猜你在找的Angularjs相关文章