我正在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
控制器方法。
答案 0 :(得分:1)
您需要提供prefix
属性。
app.useStaticAssets({
root: path.join(__dirname, '..', 'public'),
prefix: '/public/',
});
答案 1 :(得分:1)
请注意,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,无需控制器。
答案 2 :(得分:0)
对于任何人来说都是值得的;我花了一段时间,然后才意识到我的await app.listen(3000);
早于我的app.useStaticAssets(join(__dirname, '..', 'public'));
。