Angular 14使用路由时手动输入URL出现CSS/JS文件404错误
问题原因与解决办法
直接在地址栏输入http://localhost:4200/home/ingredients时页面加载失败、资源找不到,本质是Angular HTML5路由模式下的服务器重写问题:
- 点击
routerLink时是客户端路由跳转,Angular会直接处理路由逻辑,不会向服务器发送新的请求,因此资源加载正常。 - 直接访问深层路由时,浏览器会向服务器请求
/home/ingredients路径,服务器默认会寻找对应物理文件,但Angular是单页应用,所有路由都应指向根目录的index.html,服务器找不到对应文件就会返回404,进而导致CSS/JS资源加载路径错误。
解决步骤
1. 确认base href配置
你的app.component.html里已经设置了<base href="/">,这一步配置正确,它是Angular解析资源路径的基准,无需修改。
2. 开发环境临时修复
如果用ng serve启动开发服务器仍出现问题,可启动时添加--base-href /参数:
ng serve --base-href /
3. 生产/自定义服务器配置
部署到生产环境时,需配置服务器将所有路由请求重定向到index.html,以下是常见服务器的配置示例:
Nginx配置
在Nginx的server块中添加:
location / { try_files $uri $uri/ /index.html; }
Apache配置
创建或修改.htaccess文件:
RewriteEngine On RewriteBase / RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.html [L]
IIS配置
在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>
4. 备选方案:切换Hash模式路由
若不想配置服务器,可切换到Hash模式路由,修改AppRoutingModule:
@NgModule({ imports: [RouterModule.forRoot(routes, { useHash: true })], exports: [RouterModule] }) export class AppRoutingModule { }
这种模式下路由会变为http://localhost:4200/#/home/ingredients,服务器仅处理根路径请求,避免了重写问题,但URL会带有#符号。
内容的提问来源于stack exchange,提问作者freestar
相关产品推荐
相关产品推荐

