AngularJS routing without the hash '#' - c

2019-07-18 17:17发布

I have read this post many times, and I have followed the instructions there, but I cannot get this to work.

AngularJS routing without the hash '#'

I have a Qt app that sends a request to a URL with a # in it. That URL is routed to the Angular code. I want to change this to not require the #.

This is my Angular code:

angular.module('app').config(function($routeProvider, $locationProvider) {
    $routeProvider

        // route for the home page
        .when('/', {
            templateUrl : 'home.html',
            controller  : 'home'
        })

        // route for the workitem page
        .when('/workitem/:identifier', {
            templateUrl : 'workitem.html',
            controller  : 'workitem'
        });
        $locationProvider.html5Mode(true);

});  

This is my nginx config:

server {
        listen 8000;
        server_name foo.bar.com;

        location / {
            include /usr/local/nginx/conf/mime.types;
            root /projects/larry/web;
        }
    }

In /projects/larry/web there is an index.html, which loads the JS module with the $routeProvider.

When I go to the URL: http://foo.bar.com:8000/#/workitem/12345 this works fine. The JS is loaded, and the $routeProvider gets the URL and does what it's supposed to do.

But if I omit the # and go to http://foo.bar.com:8000/workitem/12345 then the JS code is not loaded and the request fails.

How can I make this work without the hash?

1条回答
【Aperson】
2楼-- · 2019-07-18 18:12

You also need to add the <base href="/" /> in the <head> of your html page.

Example below.

<!DOCTYPE html>
<html ng-app="app">
<head>
    <title>My Website</title>
    <base href="/" />
</head>
<body>

</body>
</html>

EDIT

This will take you to a GitHub post with the answer. https://gist.github.com/cjus/b46a243ba610661a7efb

查看更多
登录 后发表回答