user7350714
user7350714

Reputation: 365

Issue after removing # from url in angular $locationProvider

In my app.js I have

 $routeProvider
  .when('/', {
    templateUrl: '/views/main.html'
  })
  .when('/admin', {
    templateUrl: 'views/admin.html',
    controller: 'admin',
  })

so my routes are localhost:3000/#/ and on click of button it takes me to localhost:3000/#/admin I wanted to remove # from my url so I used

$locationProvider.html5Mode({
  enabled: true,
  requireBase: false
});

now localhost:3000/ is working and on click of button it takes me to localhost:3000/admin.

But if I directly give localhost:3000/admin in url,it is giving Cannot Get /admin..But if give localhost:3000/#/admin,it is taking me to localhost:3000/admin.Why this behaviour how can I make localhost:3000/admin to work.Can someone help

Upvotes: 1

Views: 68

Answers (3)

kaxi1993
kaxi1993

Reputation: 4700

  1. Move this line

    app.use(express.static(path.join(__dirname, 'public')));

    before app.use(app.router); in app.js file

  2. add this line in javascripts/app.js

    $locationProvider.html5Mode({ enabled: true, requireBase: false });

  3. add this code

    app.get('*', function(req, res) { res.render('index', { title: 'Express' }); });

    in app.js before http.createServer(app) line

Upvotes: 1

Harsh
Harsh

Reputation: 11

Please update your html as below:

in the head section , please use 'base' tag. So head tag will look like something :

<html>
  <head>
    <base href="/">
  </head>
</html>

then try using the URL 'localhost:3000/admin' Let me know if this helps.

Upvotes: 0

rsp
rsp

Reputation: 111336

You would need to make all of those routes return the same HTML and other assets, so that the first request to a given URL returns the correct HTML.

With the '#' it's much easier because everything from '#' to the end of the URL is not sent in the request to the server, so the server doesn't have to do anything.

But for urls without the '#' the entire URL is sent to the server so the server has to know what to serve, and the client has to be able to load a correct view depending on which URL was used in the first page load.

With no backend code provided it's hard to tell anything specific, but you have to make sure that:

  1. for every request like http://localhost:3000/admin the same HTML is returned as for http://localhost:3000/
  2. you use only absolute URLs in your HTML for CSS and client-side JavaScript
  3. your client-side code shows a correct view on the first load
  4. your client-side changes the view on every URL change like it did with '#'

Upvotes: 0

Related Questions