javascript - 如何在 Nest.js 中提供静态 HTML 文件?

标签 javascript node.js express nestjs static-files

我想提供位于 Nest 项目之外的 /dist 文件夹中的静态 HTML 文件。 index.html 已成功加载,但无法加载任何 JS 文件(404 错误)。

我有一个使用

的 Node/Express.js 项目
app.use('/', express.static('../client/dist'))

而且它工作得很好。

然而,在 Nest 项目中,

app.setBaseViewsDir(join(__dirname, '../../client/dist'))

不成功。

AppController 我试过了

import { Response } from 'express';

@Get()
  get(@Res() res: Response) {
    res.sendFile('index.html', {
      root: '../client/dist',
    });
  }

但没有运气。

如前所述,index.html 已成功加载。所以问题不是错误的路径。问题也不是 index.html 中错误的 src 路径,因为在 Express 项目中使用了完全相同的文件。

/dist
  |-index.html
  |-main.js
  |-etc.

在 index.html 中:

<script type="text/javascript" src="main.js"></script>

当我将 dist 文件夹放入 Nest 项目(并调整路径)时,它也不起作用。

我找到了解决方案:

我现在使用 express 模块:

import * as express from 'express';
...
app.use('/', express.static('../client/dist'));

最佳答案

关于 official documentation Nest.js 应该像这样提供静态文件:

安装所需的包:

npm install --save @nestjs/serve-static

更新app.module.ts看起来像这样:

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ServeStaticModule } from '@nestjs/serve-static';
import { join } from 'path';

@Module({
  imports: [
    ServeStaticModule.forRoot({
      rootPath: join(__dirname, '..', 'client'),   // <-- path to the static files
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

关于javascript - 如何在 Nest.js 中提供静态 HTML 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55325062/

相关文章:

node.js - 如何在 Express 项目中正确布置 Mongoose?

javascript - mvc.net 4 ajax 使用操作 httpGet 不适用于 httpPost

javascript - Node.js Bluebird Promise 提示 "Converting circular structure to JSON"

javascript - 如何在 swaggerexpress 中附加中间件,如express-validator

javascript - Express + PassportJs : Why do we need to delay the execution of method with process. Passport 策略中的 nextTick()?

python - 在 Cygwin 上构建 node.js 的问题,请帮忙

javascript - 重新加载 iframe 时捕获 javascript 事件

javascript - 带有动态js对象变量作为属性的jade mixin

javascript - 如何通过先浏览将文本文件中的内容或html文件中的html代码加载到文本区域?

javascript - Linux 操作系统上的 ibm_db 模块安装问题