You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

开启Angular ui-router的html5Mode后刷新页面出现Cannot GET /的解决方法

修复AngularJS开启html5Mode后刷新页面"Cannot GET /"的问题

问题根源

开启$locationProvider.html5Mode(true)后,URL不再包含#锚点。刷新页面时,浏览器会直接向服务器请求当前URL路径(比如/en/intro),但服务器没有配置对应路径的静态资源或路由规则,因此返回404错误。

解决步骤

1. 前端补充配置

在项目的index.html根文件中添加<base>标签,这是html5Mode正常工作的必要条件:

<head>
  <!-- 其他head内容 -->
  <base href="/">
</head>

另外,检查你的路由otherwise逻辑:当前代码中跳转到app.intro时没有传入lang参数(app是带:lang参数的抽象状态),会导致路由跳转失败,建议修改otherwise逻辑,指定默认语言参数:

$urlRouterProvider.otherwise(function($injector, $location){
    let $state = $injector.get("$state");
    // 指定默认lang为'en'
    $state.go("app.intro", { lang: "en" });
});

2. 服务器端配置(核心修复)

需要让服务器将所有非静态资源的请求都转发到index.html,由AngularJS的ui-router来处理路由。以下是常见服务器的配置方式:

Express服务器

安装connect-history-api-fallback中间件:

npm install connect-history-api-fallback --save

在Express入口文件中添加:

const express = require('express');
const history = require('connect-history-api-fallback');
const app = express();

// 先配置静态资源目录
app.use(express.static(__dirname + '/dist'));
// 添加history fallback中间件
app.use(history());
// 再次配置静态资源(确保fallback后能正确加载index.html)
app.use(express.static(__dirname + '/dist'));

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

Nginx服务器

修改Nginx配置文件(比如nginx.conf或站点配置),在location块中添加try_files规则:

server {
  listen 80;
  server_name your-domain.com;
  root /path/to/your/project/dist;

  location / {
    try_files $uri $uri/ /index.html;
  }
}

修改后重启Nginx生效。

Apache服务器

在项目根目录创建.htaccess文件,添加以下内容:

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>

确保Apache开启了mod_rewrite模块。

内容的提问来源于stack exchange,提问作者made wirawan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 07:53:29