Reloading the page gives wrong GET request with AngularJS HTML5 mode

前端 未结 24 2896
慢半拍i
慢半拍i 2020-11-22 01:39

I want to enable HTML5 mode for my app. I have put the following code for the configuration, as shown here:

return app.config([\'$routeProvider\',\'$location         


        
相关标签:
24条回答
  • 2020-11-22 01:50

    I have found even better Grunt plugin, that works if you have your index.html and Gruntfile.js in the same directory;

    https://npmjs.org/package/grunt-connect-pushstate
    

    After that in your Gruntfile:

     var pushState = require('grunt-connect-pushstate/lib/utils').pushState;
    
    
        connect: {
        server: {
          options: {
            port: 1337,
            base: '',
            logger: 'dev',
            hostname: '*',
            open: true,
            middleware: function (connect, options) {
              return [
                // Rewrite requests to root so they may be handled by router
                pushState(),
                // Serve static files
                connect.static(options.base)
              ];
            }
          },
        }
    },
    
    0 讨论(0)
  • 2020-11-22 01:51

    For Grunt and Browsersync use connect-modrewrite here

    var modRewrite = require('connect-modrewrite');    
    
    
    browserSync: {
                dev: {
                    bsFiles: {
    
                        src: [
                            'app/assets/css/*.css',
                            'app/*.js',
                            'app/controllers/*.js',
                            '**/*.php',
                            '*.html',
                            'app/jade/includes/*.jade',
                            'app/views/*.html',
                   ],
                },
            options: {
                watchTask: true,
                debugInfo: true,
                logConnections: true,
                server: {
                    baseDir :'./',
                    middleware: [
                           modRewrite(['!\.html|\.js|\.jpg|\.mp4|\.mp3|\.gif|\.svg\|.css|\.png$ /index.html [L]'])
                    ]
                },
    
                ghostMode: {
                    scroll: true,
                    links: true,
                    forms: true
                        }
                    }
                }
            },
    
    0 讨论(0)
  • 2020-11-22 01:52
    I solved same problem using modRewrite.  
    AngularJS is reload page when after # changes.  
    But HTML5 mode remove # and invalid the reload.  
    So we should reload manually.
    # install connect-modrewrite
        $ sudo npm install connect-modrewrite --save
    
    # gulp/build.js
        'use strict';
        var gulp = require('gulp');
        var paths = gulp.paths;
        var util = require('util');
        var browserSync = require('browser-sync');
        var modRewrite  = require('connect-modrewrite');
        function browserSyncInit(baseDir, files, browser) {
            browser = browser === undefined ? 'default' : browser;
            var routes = null;
            if(baseDir === paths.src || (util.isArray(baseDir) && baseDir.indexOf(paths.src) !== -1)) {
                routes = {
                    '/bower_components': 'bower_components'
                };
            }
    
            browserSync.instance = browserSync.init(files, {
                startPath: '/',
                server: {
                baseDir: baseDir,
                middleware: [
                    modRewrite([
                        '!\\.\\w+$ /index.html [L]'
                    ])
                ],
                routes: routes
                },
                browser: browser
            });
        }
    
    0 讨论(0)
  • 2020-11-22 01:53

    I'm answering this question from the larger question:

    When I add $locationProvider.html5Mode(true), my site will not allow pasting of urls. How do I configure my server to work when html5Mode is true?

    When you have html5Mode enabled, the # character will no longer be used in your urls. The # symbol is useful because it requires no server side configuration. Without #, the url looks much nicer, but it also requires server side rewrites. Here are some examples:

    For Express Rewrites with AngularJS, you can solve this with the following updates:

    app.get('/*', function(req, res) {
    res.sendFile(path.join(__dirname + '/public/app/views/index.html'));
    });
    

    and

    <!-- FOR ANGULAR ROUTING -->
    <base href="/">
    

    and

    app.use('/',express.static(__dirname + '/public'));
    
    0 讨论(0)
  • 2020-11-22 01:56

    If you are in .NET stack with MVC with AngularJS, this is what you have to do to remove the '#' from url:

    1. Set up your base href in your _Layout page: <head> <base href="/"> </head>

    2. Then, add following in your angular app config : $locationProvider.html5Mode(true)

    3. Above will remove '#' from url but page refresh won't work e.g. if you are in "yoursite.com/about" page refresh will give you a 404. This is because MVC does not know about angular routing and by MVC pattern it will look for a MVC page for 'about' which does not exists in MVC routing path. Workaround for this is to send all MVC page request to a single MVC view and you can do that by adding a route that catches all url


    routes.MapRoute(
            name: "App",
            url: "{*url}",
            defaults: new { controller = "Home", action = "Index" }
        );
    
    0 讨论(0)
  • 2020-11-22 01:56

    As others have mentioned, you need to rewrite routes on the server and set <base href="/"/>.

    For gulp-connect:

    npm install connect-pushstate

    var gulp = require('gulp'),
      connect = require('gulp-connect'),
      pushState = require('connect-pushstate/lib/pushstate').pushState;
    ...
    connect.server({
      ...
      middleware: function (connect, options) {
        return [
          pushState()
        ];
      }
      ...
    })
    ....
    
    0 讨论(0)
提交回复
热议问题