在 NestJS 中配置静态资源服务器并访问图片

1,879 阅读1分钟

在 NestJS 中配置静态资源服务器并访问图片

完整步骤:

  1. 在 main.ts 中导入 express 和 path 模块:

    import * as express from 'express';
    import * as path from 'path';
    
  2. 在 bootstrap() 方法中创建 Nest 应用程序实例,并使用 express.static() 中间件设置静态资源目录:

   async function bootstrap() {
     const app = await NestFactory.create(AppModule);
   
     // 将 dist/public 目录设置为静态资源目录
     app.use(express.static(path.join(__dirname, '..', 'dist', 'public')));
   
     await app.listen(3000);
   }

在上面的代码中,我们将 dist/public 目录设置为静态资源目录。您可以根据自己的需要更改目录路径。

  1. 在 public 目录下创建 images 目录,并将要访问的图片放入其中。

  2. 启动 Nest 应用程序,并使用以下 URL 格式来访问图片:

    http://localhost:3000/images/<图片文件名>

    例如,如果您要访问名为 example.png 的图片,您可以使用以下 URL:

    http://localhost:3000/images/example.png

这样,您就可以将 NestJS 配置为静态资源服务器,并通过 URL 访问图片了。请注意,如果您在 URL 中使用的文件名或路径包含非 ASCII 字符,可能需要对其进行编码。