refreshing the page results in 404 error- Angular 6

后端 未结 10 1723
广开言路
广开言路 2020-12-05 06:54

I am building an application with the help of Angular6 and facing problems in routing. All the routes are working when I click on a particu

相关标签:
10条回答
  • 2020-12-05 07:11

    In my case i did following thing

    Method 1 :

    in your app.module.ts import below thing

    import { HashLocationStrategy, LocationStrategy } from '@angular/common';
    @NgModule({
      declarations: [...],
      imports: [...],
      providers: [{provide: LocationStrategy, useClass: HashLocationStrategy}],
      bootstrap: [AppComponent]
    })
    

    and build with

    ng build --base-href /[PROJECT_NAME]/

    method 2 :

    for nginx,

    nano /etc/nginx/sites-available/default

    add follwing line in location block

    location /[PROJECT_NAME] {
      try_files $uri $uri/ /[PROJECT_NAME]/index.html;
    }
    

    sudo service nginx restart

    and build with

    ng build --base-href /[PROJECT_NAME]/

    0 讨论(0)
  • 2020-12-05 07:12

    To avoid using hashed routes, you must edit your webserver configuration properly, which is the best solution. You just have to configure it so it fallbacks to index.html, which is Angular's bootstrap. Although there is no universal configuration for this, here are some:

    Apache

    Add a rewrite rule to .htaccess file

    RewriteEngine On
    # If an existing asset or directory is requested go to it as it is
    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
    RewriteRule ^ - [L]
    
    # If the requested resource doesn't exist, use index.html
    RewriteRule ^ /index.html
    

    Nginx

    Use try_files in your location block

    try_files $uri $uri/ /index.html;
    

    IIS

    Add a rewrite rule to web.config

    <system.webServer>
      <rewrite>
        <rules>
          <rule name="Angular Routes" stopProcessing="true">
            <match url=".*" />
            <conditions logicalGrouping="MatchAll">
              <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
              <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
            </conditions>
            <action type="Rewrite" url="/index.html" />
          </rule>
        </rules>
      </rewrite>
    </system.webServer>
    

    GitHub Pages

    You can't configure it directly, but you can add a 404 page. Copy index.html into 404.html in the same directory or add a symlink: ln -s index.html 404.html.

    Firebase hosting

    Add a rewrite rule.

    "rewrites": [ {
      "source": "**",
      "destination": "/index.html"
    } ]
    

    Source: https://angular.io/guide/deployment#server-configuration

    0 讨论(0)
  • 2020-12-05 07:16

    With .htaccess you can try with following way also:

    <IfModule mod_rewrite.c>
        RewriteEngine on
    
        # Don't rewrite files or directories
        RewriteCond %{REQUEST_FILENAME} -f [OR]
        RewriteCond %{REQUEST_FILENAME} -d
        RewriteRule ^ - [L]
    
        # Rewrite everything else to index.html
        # to allow html5 state links
        RewriteRule ^ index.html [L]
    </IfModule>
    
    0 讨论(0)
  • 2020-12-05 07:22

    I think you are getting 404 because your are requesting http://localhost/route which doesn't exist on tomcat server. As Angular 2 uses html 5 routing by default rather than using hashes at the end of the URL, refreshing the page looks like a request for a different resource.

    When using angular routing on tomcat you need to make sure that your server will map all routes in your app to your main index.html while refreshing the page. There are multiple way to resolve this issue. Whichever one suits you you can go for that.

    1) Put below code in web.xml of your deployment folder :

    <error-page>
         <error-code>404</error-code>
         <location>/index.html</location>
    </error-page>
    

    2) You can also try using HashLocationStrategy with # in the URL for routes :

    Try using:

    RouterModule.forRoot(routes, { useHash: true })

    Instead of:

    RouterModule.forRoot(routes)

    With HashLocationStrategy your urls gonna be like:

    http://localhost/#/route

    3) Tomcat URL Rewrite Valve : Re-write the url's using a server level configuration to redirect to index.html if the resource is not found.

    3.1) Inside META-INF folder create a file context.xml and copy the below context inside it.

    <? xml version='1.0' encoding='utf-8'?>
    <Context>
      <Valve className="org.apache.catalina.valves.rewrite.RewriteValve" />
    </Context>
    

    3.2) Inside WEB-INF, create file rewrite.config(this file contain the rule for URL Rewriting and used by tomcat for URL rewriting). Inside rewrite.config, copy the below content:

    RewriteCond %{SERVLET_PATH} !-f

    RewriteRule ^/(.*)$ /index.html [L]

    0 讨论(0)
  • 2020-12-05 07:22

    Starting with Apache 2.4, you can use the FallbackResource directive instead of rewriting, so it will look like:

    FallbackResource /index.html
    

    If you have a different base href (say, /awesomeapp), change it for:

    <Location /awesomeapp>
        FallbackResource /awesomeapp/index.html
    </Location>
    
    0 讨论(0)
  • 2020-12-05 07:29

    Add .htaccess file to your src folder.

    .htaccess file

    <IfModule mod_rewrite.c>
        RewriteEngine on
    
        # Don't rewrite files or directories
        RewriteCond %{REQUEST_FILENAME} -f [OR]
        RewriteCond %{REQUEST_FILENAME} -d
        RewriteRule ^ - [L]
    
        # Rewrite everything else to index.html
        # to allow html5 state links
        RewriteRule ^ index.html [L]
    </IfModule>
    

    Load .htaccess file in your build directory dist by adding it to assets in angular.json

    "assets": [
         "src/favicon.ico",
         "src/assets",
         "src/.htaccess"
    ],
    
    0 讨论(0)
提交回复
热议问题