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

Angular 17项目部署后刷新页面出现404错误求助

Angular 17 刷新页面404问题解决(HashLocationStrategy 配置方法)

这个问题的核心原因是:Angular是单页应用(SPA),默认使用HTML5模式路由,刷新页面时服务器会尝试请求对应路径的物理文件,但这些文件实际不存在,因此返回404。使用哈希模式路由后,路由路径会被放到URL的#之后,服务器只会处理#之前的根路径,Angular会自行解析#后的路由内容,避免404。

以下是Angular 17中的两种配置方法:

方法一:使用路由内置配置项(推荐)

  1. 打开app.config.ts,导入withHashLocation:
import { provideRouter, withHashLocation } from '@angular/router';
import { routes } from './app.routes';
  1. 修改provideRouter的调用,添加withHashLocation()作为第二个参数:
export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes, withHashLocation()),
    // 保留其他已有的providers配置
  ]
};

方法二:手动注入HashLocationStrategy

如果需要自定义路由策略的初始化逻辑,可以用这种方式:

  1. 在app.config.ts中导入相关依赖:
import { provideLocationStrategy, HashLocationStrategy } from '@angular/common';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
  1. 在providers数组中添加策略配置:
export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes),
    provideLocationStrategy(() => new HashLocationStrategy()),
    // 保留其他已有的providers配置
  ]
};

配置完成后,重新构建Angular项目并部署到服务器,刷新页面就不会触发404了。此时URL会自动添加#前缀(比如/#/user/detail),但正常访问组件的逻辑不受影响。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 08:34:57