我想提供静态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'));
要提供静态文件,您必须使用useStaticAssets()
而不是setBaseViewsDir()
:
app.useStaticAssets(join(__dirname, '../../client/dist'))
当您使用useStaticAssets
时,您不需要设置控制器,您的所有文件都将自动提供:
让我们说在client/dist
下你有文件index.html
和pic.jpg
。他们将作为:
localhost:3000 -> index.html
localhost:3000/pic.jpg -> pic.jpg
如果要使用视图引擎(例如hbs
),则需要设置基本视图目录,请参阅docs。
在main.ts中写app.useStaticAssets(join(__dirname, '../../client/dist'))
而你也可以尝试使用这个:
import { resolve } from 'path';
app.useStaticAssets({
root: resolve("./build")
});