Html5Mode - refreshing the angularjs page issue

假装没事ソ 提交于 2019-12-18 09:47:50

问题


I am working on an angularJS app, which has URLs in the format (in dev) -

http://localhost:6001/#/home/index
http://localhost:6001/#/content/index

As this app, will also be available on desktop browser, I wanted the URLs to be without '#', so I added this in my app's config section -

$locationProvider.html5Mode(true);

Which works fine and URLs don't show '#'. But there is a problem now. On refreshing a particular page in browser, now I get this error -

Cannot GET /home/index

Are there any other changes required to get this working?

Note: This app is using cordova CLI and is hosted on a Node.js server.


回答1:


Try to put in your as your route:

app.get(*, function(req,res) {
  //return the main index file
});

This will cause any unmatched route to serve the index page and from there angular take care of this route.




回答2:


Try this:

  1. Make sure you have these lines in your server.js file

    var express = require('express');
    var app = express();
    app.use(express.static(__dirname + '/public.build'));
    app.use(function(req, res) {
    res.sendFile('index.html', { root: __dirname + "/public.build" });
    });
    

    Why so? Please read here - https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#how-to-configure-your-server-to-work-with-html5mode

  2. The first step resulted in my app in the following console.log message:

    Resource interpreted as Stylesheet but transferred with MIME type
    text/html: "http://localhost:8080/board/css/style.css". 
    

    As you can see, the styles are trying to load from non-existent path (/board/ folder is not present in the app, it's one of the states in ui-router). To fix it I replaced the following line

    <link rel="stylesheet" href="css/style.css">
    

    with this one:

    <link rel="stylesheet" href="/css/style.css">
    


来源:https://stackoverflow.com/questions/29343436/html5mode-refreshing-the-angularjs-page-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!