【问题标题】:How to fix Cannot GET / in Angular when refreshing the page?刷新页面时如何修复无法在Angular中获取/?
【发布时间】:2019-01-23 17:37:10
【问题描述】:

我是 Angular 世界的新手。我遵循 Angular.io 指南来路由我的应用程序及其许多页面。我遇到的问题是当我点击浏览器中的刷新按钮时。我是一个“无法获取 /dashboard”,我一直在研究这个问题,并且确实放置了 href="/"。

这是我的路由文件

const routes: Routes = [
  { path: 'login', component: LoginComponent },
  { path: '', component: LoginComponent },
  { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },

  { path: '**', redirectTo: '', pathMatch: 'full' }
];

@NgModule({
  imports: [
    RouterModule.forRoot(
      routes,
      {
        enableTracing: false
      }
    )],
  exports: [RouterModule]
})
export class AppRoutingModule { }

如前所述,我可以访问 url,但是当我刷新页面时,我得到“Cannot GET /dashboard” 我需要做些什么来解决这个问题吗?刷新页面时如何修复Cannot GET / in Angular?

【问题讨论】:

  • 您的服务器是否设置为无论 URL 是什么都返回基本 HTML 页面?如果没有,当您直接访问/dashboard 时,您的服务器会认为您在向它询问仪表板页面。但您确实希望服务器返回基本 HTML 页面,因此客户端路由器可以看到 /dashboard 并从那里获取它。你也可以切换到基于哈希的路由来避免这个问题。
  • 我将它托管在 IIS 服务器上,并且我将 index.html 作为默认值@FrankModica
  • 您可能需要重写 URL。查看blog.angularindepth.com/…
  • @FrankModica 你能把它作为答案,这样你就可以获得积分

标签: angular typescript angular-routing


【解决方案1】:

无论 URL 是什么,您的服务器都需要设置为返回基本 HTML 页面,这样客户端路由器就可以看到 /dashboard 并从那里获取它。否则,当您直接访问 /dashboard 时,您的服务器会认为您在向它请求仪表板页面。

您可以在 IIS 中使用 URL 重写来完成此操作。以下是来自https://blog.angularindepth.com/deploy-an-angular-application-to-iis-60a0897742e7 的示例:

<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>

另一个选项是基于哈希的 URL,可以这样完成:

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

这是可行的,因为服务器看不到 URL 的哈希部分。详情请见https://angular.io/guide/router。

【讨论】:

    【解决方案2】:

    我使用 Nodejs 来提供 Angular 文件,然后我将以下代码部分添加到 serve.js 然后它就可以工作了。

    app.route('/*').get(function (req, res) {
      return res.sendFile(path.join(staticRoot + 'index.html'));
    });
    
    

    I get this content from here

    如果你使用 Nginx 或 Apache 来提供文件,你必须使用 URLRewrite 来重定向到 index.html。服务器将客户端重定向到 index.html,它将导入 Angular 并由 RoutingModule 处理导航。

    我的serve.js 内容是:

    // index.html and its contents are inside the `html` folder
    // and the server.js is located on the same path as the `html` folder.
    var express = require('express'),
      path = require('path'),
      fs = require('fs');
    var compression = require('compression');
    var app = express();
    var staticRoot = __dirname + '/html/';
    var env = process.env.NODE_ENV || 'production';
    
    app.set('port', (process.env.PORT || 3002));
    
    app.use(compression());
    /* other middleware */
    
    /* place any backend routes you have here */
    
    app.use(function (req, res, next) {
      //if the request is not html then move along
      var accept = req.accepts('html', 'json', 'xml');
      if (accept !== 'html') {
        return next();
      }
      // if the request has a '.' assume that it's for a file, move along
      var ext = path.extname(req.path);
      if (ext !== '') {
        return next();
      }
      fs.createReadStream(staticRoot + 'index.html').pipe(res);
    });
    
    app.use(express.static(staticRoot));
    
    /**
    * Redirect to index.html
    */
    app.route('/*').get(function (req, res) {
      return res.sendFile(path.join(staticRoot + 'index.html'));
    });
    
    
    app.listen(app.get('port'), function () {
      console.log('app running on port', app.get('port'));
    });
    

    【讨论】:

      猜你喜欢
      • 2020-08-15
      • 1970-01-01
      • 1970-01-01
      • 2015-02-22
      • 2017-02-20
      • 1970-01-01
      • 2020-03-06
      • 1970-01-01
      • 2012-02-01
      相关资源
      最近更新 更多