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

问题描述 投票:2回答:2

我想提供静态HTML文件,这些文件位于Nest项目之外的/dist文件夹中。 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-path错误,因为在Express项目中使用了完全相同的文件。

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

在index.html中:

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

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

我找到了解决方案:

我现在使用快递模块:

import * as express from 'express';
...
app.use('/', express.static('../client/dist'));
javascript node.js express nestjs static-files
2个回答
0
投票

要提供静态文件,您必须使用useStaticAssets()而不是setBaseViewsDir()

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

当您使用useStaticAssets时,您不需要设置控制器,您的所有文件都将自动提供:

让我们说在client/dist下你有文件index.htmlpic.jpg。他们将作为:

localhost:3000 -> index.html
localhost:3000/pic.jpg -> pic.jpg

如果要使用视图引擎(例如hbs),则需要设置基本视图目录,请参阅docs


0
投票

在main.ts中写app.useStaticAssets(join(__dirname, '../../client/dist'))

而你也可以尝试使用这个:

import { resolve } from 'path';

app.useStaticAssets({
    root: resolve("./build")
  });
© www.soinside.com 2019 - 2024. All rights reserved.