问题描述
我开始学习MEAN堆栈,当我去Express时,我发现Express框架中存在一个称为nestJS的额外层。它具有我想要的所有内容,并且具有类似Angular的语法,因此对我来说很完美。
但是每一个新步骤都是一场噩梦,文档根本没有用。现在,我正在与该框架进行斗争,以实现提供图像并且不将API用于此类调用。
我尝试了在Internet上找到的所有内容,例如:
main.ts
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 (https://docs.nestjs.com/techniques/mvc) (https://whatthecode.dev/serve-static-files-with-nest-js/)
app.use('/resources',express.static(process.cwd() + '\\resources'));
app.useStaticAssets(join(__dirname,'\\public'));
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ limit: '50mb',extended: true }));
//console.log(process.cwd());
await app.listen(3000);
if (module.hot) {
module.hot.accept();
module.hot.dispose(() => app.close());
}
}
bootstrap();
我试图将其放置在app.module中(它可以工作,但总是在寻找index.html而不是图片):
import { AnimalsModule } from './animals/animals.module';
import { SpeciesModule } from './species/species.module';
import { AuthModule } from './auth/auth.module';
import { UsersModule } from './users/users.module';
import { BreedModule } from './breed/breed.module';
import { StateModule } from './state/state.module';
import { PhotoModule } from './photo/photo.module';
@Module({
imports: [
ServeStaticModule.forRoot({
rootPath: join(__dirname,'public'),// <-- path to the static files
}),TypeOrmModule.forRoot({
type: 'MysqL',host: 'localhost',port: 3306,username: 'root',password: '',database: 'nest',entities: [__dirname + '/**/*.entity{.ts,.js}'],synchronize: true,}),AnimalsModule,SpeciesModule,BreedModule,StateModule,AuthModule,UsersModule,PhotoModule,],})
//It seems that ignores this register and just uses the method signature options
@Module({
imports: [MulterModule.register({
dest: './resources/tmp',limits: { fieldSize: 25 * 1024 * 1024 * 1024,fileSize: 25 * 1024 * 1024 * 1024 }
})],controllers: [AppController],providers: [AppService],})
export class AppModule { }
感谢所有人。
解决方法
这就是我所做的:
-
在app.module.ts中
import { ServeStaticModule } from '@nestjs/serve-static/dist/serve-static.module'; import { join } from 'path'; @Module({ imports: [ ServeStaticModule.forRoot({ rootPath: join(__dirname,'..','public'),}),],})
-
然后我在与“ src”,“ dir”等相同的级别上创建了“ public”目录。
-
该文件位于:https://my-url/file.jpg
将此添加到 main.ts 用您的目录名称替换“上传” app.use('/uploads',express.static(join(process.cwd(),'uploads')));