NestJS服务下使用@font-face时浏览器无法获取woff字体文件求助
NestJS 字体静态资源加载异常解决方案
两类异常的核心原因是 NestJS 默认没有对外暴露静态资源目录,你存放字体的fonts目录未完成服务端路由映射,导致客户端请求无法定位到对应文件。
步骤1:注册静态资源目录
首先根据你使用的服务适配器,完成fonts目录的路由映射配置:
1.1 Express 适配器(NestJS 默认适配器)
先安装静态资源服务依赖:
npm install @nestjs/serve-static
在app.module.ts中注册目录映射:
import { Module } from '@nestjs/common'; import { ServeStaticModule } from '@nestjs/serve-static'; import { join } from 'path'; @Module({ imports: [ ServeStaticModule.forRoot({ // 填写fonts目录的物理存储路径 rootPath: join(__dirname, '..', 'fonts'), // 配置对外访问的路由前缀 serveRoot: '/fonts', }), ], }) export class AppModule {}
1.2 Fastify 适配器
先安装Fastify静态资源依赖:
npm install @fastify/static
在main.ts中注册目录映射:
import { NestFactory } from '@nestjs/core'; import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify'; import { AppModule } from './app.module'; import { join } from 'path'; async function bootstrap() { const app = await NestFactory.create<NestFastifyApplication>( AppModule, new FastifyAdapter() ); app.register(require('@fastify/static'), { root: join(__dirname, '..', 'fonts'), prefix: '/fonts/', }); await app.listen(3000); } bootstrap();
步骤2:修正@font-face路径配置
使用绝对路径配置字体地址,避免页面路由层级变化导致的相对路径解析错误:
@font-face { font-family: Roboto; src: url(/fonts/roboto-v29-latin-regular.woff); }
异常问题排查
如果配置后仍有问题,检查以下两点:
- 确认
fonts目录会被拷贝到编译后的dist目录中,TypeScript项目默认不会打包非TS后缀文件,需要在nest-cli.json中配置资源拷贝规则:{ "compilerOptions": { "assets": ["fonts/**/*"] } } - 确认全局拦截器、守卫没有拦截静态资源的GET请求,避免返回默认空对象响应。
内容的提问来源于stack exchange,提问作者tomwe
相关产品推荐
相关产品推荐

