我想提供/dist位于 Nest 项目外部文件夹中的静态 HTML 文件。index.html已成功加载但无法加载任何 JS 文件(404错误)。
我有一个 Node/Express.js 项目,它使用
app.use('/', express.static('../client/dist'))
Run Code Online (Sandbox Code Playgroud)
它工作得很好。
然而,在 Nest 项目中,
app.setBaseViewsDir(join(__dirname, '../../client/dist'))
Run Code Online (Sandbox Code Playgroud)
不做的伎俩。
在AppController我试过
import { Response } from 'express';
@Get()
get(@Res() res: Response) {
res.sendFile('index.html', {
root: '../client/dist',
});
}
Run Code Online (Sandbox Code Playgroud)
但没有运气。
如前所述,index.html已成功加载。所以问题不是走错路。问题也不是 src-paths 错误,index.html因为在 Express 项目中使用了完全相同的文件。
/dist
|-index.html
|-main.js
|-etc.
Run Code Online (Sandbox Code Playgroud)
在 index.html 中:
<script type="text/javascript" src="main.js"></script>
Run Code Online (Sandbox Code Playgroud)
当我将 dist 文件夹放入 Nest 项目(并调整路径)时,它也不起作用。
我现在使用 express 模块:
import * as express from 'express'; …Run Code Online (Sandbox Code Playgroud) 我开始学习 MEAN 堆栈,当我去 Express 时,我看到在 Express 框架中存在一个额外的层,称为 NestJS。它拥有我想要的一切,并且具有类似 Angular 的语法,因此对我来说非常完美。
但是每一个新步骤都是一场噩梦,文档根本没有用。现在我正在与框架斗争以实现提供图像并且不使用 API 进行此类调用。
我尝试了我在互联网上找到的所有内容,例如:
主文件
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as bodyParser from 'body-parser';
import * as express from 'express';
import { join } from 'path';
import { NestExpressApplication } from '@nestjs/platform-express';
declare const module: any;
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(AppModule);
app.useStaticAssets(join(__dirname, '..', 'public'));
app.enableCors({
origin: true,
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
credentials: true,
});
//I tried this 2 options …Run Code Online (Sandbox Code Playgroud)