我在main.ts
中配置静态文件文件夹
app.useStaticAssets({
root: path.resolve(__dirname + '/public'),
});
现在在运行时我有一个错误TypeError: root path must be a string
我试图使用path.join(__dirname + '/public'),
- 没有帮助。
我像import * as path from 'path'
一样导入路径
任何想法如何解决?
更新:根据上面的答案,我正在尝试:
app.useStaticAssets(join(__dirname, '..', 'public'));
- 得到错误{"statusCode":404,"error":"Not Found","message":"Cannot GET /"}
还尝试过:
app.useStaticAssets({
root: path.join(__dirname, '..', 'public'),
prefix: '/public/',
});
仍然与这一个相同的错误 - TypeError: root path must be a string
我的控制器方法如下:
@Get()
root(@Res() res) {
res.sendFile('index.html');
}
更新:如果我有app.useStaticAssets(path.join(__dirname, '..', 'public'));
并删除root
控制器方法仍然有404
错误。
您需要提供prefix
财产。
app.useStaticAssets({
root: path.join(__dirname, '..', 'public'),
prefix: '/public/',
});
请注意,对于express和fastify,配置是不同的:
app.useStaticAssets(join(__dirname, '..', 'public'));
app.useStaticAssets({
root: join(__dirname, '..', public'),
prefix: '/public/',
});
join
直接导入示例中。
import { join } from 'path';
如果您要提供静态内容,则无需添加特定控制器;资产将通过中间件自动提供。
让我们假设您在/public
下有两个文件:index.html
和image.png
localhost:3000
和localhost:3000/index.html
为index.html
服务localhost:3000/image.png
为image.png
服务没有控制器,请看这个简单的codesandbox example。