首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用fastify在NestJS中提供静态文件?

如何使用fastify在NestJS中提供静态文件?
EN

Stack Overflow用户
提问于 2022-11-04 17:37:27
回答 1查看 90关注 0票数 1

如何使用fastify在NestJS中提供静态文件?我似乎找不到最近的任何适当设置的例子。我的main.ts设置如下:

main.ts

代码语言:javascript
运行
复制
// This must be the first thing imported in the app
import 'src/tracing';

import * as winston from 'winston';
import fastifyStatic, { FastifyStaticOptions } from '@fastify/static';
import { NestFactory } from '@nestjs/core';
import {
  FastifyAdapter,
  NestFastifyApplication,
} from '@nestjs/platform-fastify';
import { path } from 'app-root-path';
import { WinstonModule } from 'nest-winston';
import { doc } from 'prettier';

import { AppModule } from 'src/app.module';

import join = doc.builders.join;

async function bootstrap() {
  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    new FastifyAdapter(),
    {
      logger: WinstonModule.createLogger({
        format: winston.format.combine(
          winston.format.timestamp(),
          winston.format.json(),
        ),
        transports: [new winston.transports.Console()],
      }),
      rawBody: true,
    },
  );

  await app.register(require('@fastify/static'), {
    root: require('app-root-path').resolve('/client'),
    prefix: '/client/', // optional: default '/'
  });

  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-ignore
  app.get('/another/path', function (req, reply) {
    reply.sendFile('index.html');
  });

  app.enableShutdownHooks(); // terminus needs this to listen for SIGTERM/SIGKILL
  await app.listen(3002, '0.0.0.0');
  console.log(`Application is running on: ${await app.getUrl()}`);
}
bootstrap();

我试图提供的静态文件是client/index.html

然而,当我运行我的应用程序时,我会得到以下错误:Nest could not find /another/path element (this provider does not exist in the current context)

我也尝试过设置我的app.module.ts模块如下:

app.module.ts

代码语言:javascript
运行
复制
@Module({
  imports: [
    ...configModules,
    ...domainModules,
    ...libraryModules,
    ServeStaticModule.forRoot({
      rootPath: require('app-root-path').resolve('/client'),
      renderPath: '/client/*',
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})

这将导致以下错误:

代码语言:javascript
运行
复制
/Users/ewu/Desktop/Projects/janus/node_modules/@nestjs/platform-fastify/node_modules/fastify/lib/route.js:286
            throw new FST_ERR_DUPLICATED_ROUTE(opts.method, opts.url)
                  ^
FastifyError: Method 'HEAD' already declared for route '/'
    at Object.addNewRoute (/Users/ewu/Desktop/Projects/janus/node_modules/@nestjs/platform-fastify/node_modules/fastify/lib/route.js:286:19)
    at Object.route (/Users/ewu/Desktop/Projects/janus/node_modules/@nestjs/platform-fastify/node_modules/fastify/lib/route.js:211:19)
    at Object.prepareRoute (/Users/ewu/Desktop/Projects/janus/node_modules/@nestjs/platform-fastify/node_modules/fastify/lib/route.js:144:18)
    at Object._head [as head] (/Users/ewu/Desktop/Projects/janus/node_modules/@nestjs/platform-fastify/node_modules/fastify/fastify.js:247:34)
    at fastifyStatic (/Users/ewu/Desktop/Projects/janus/node_modules/@fastify/static/index.js:370:17)

以下是相关的软件包及其版本:

代码语言:javascript
运行
复制
"@nestjs/serve-static": "^3.0.0",
"fastify-static": "^4.7.0",
"fastify": "^4.8.1",
"@nestjs/platform-fastify": "^9.1.2",
"@fastify/static": "^6.0.0",

我正在使用Nest的9.0.0版本和Node的16.15.0版本。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-11-04 18:54:53

您很可能在@Controller() (很可能是您的AppController)下有一个GET /,它已经绑定了GET /路由。Fastify不允许将两个处理程序绑定到同一条路由。因此,您需要更改@Get()以具有与其关联的某种路由,将ServeStaticModule更改为具有不同的服务路由,或者使用全局前缀来修改其余的服务器路由(我相信这会使服务器静态模块不受影响)。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74320998

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档