Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

nestjs 如何渲染静态目录 #9

Open
hongrunhui opened this issue Oct 13, 2019 · 3 comments
Open

nestjs 如何渲染静态目录 #9

hongrunhui opened this issue Oct 13, 2019 · 3 comments

Comments

@hongrunhui
Copy link

代码实现如下:
app.module.ts

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ServeStaticModule } from '@nestjs/serve-static';
import { join } from 'path';
@Module({
  imports: [
    ServeStaticModule.forRoot({
      rootPath: join(__dirname, '..', 'front-end/dist'),   // <-- path to the static files
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

这样虽然渲染出来了,但是其他的API接口就不能用了,
如在控制器app.controller.ts

  @Get('api/:name')
  hello(@Param() params, @Req() request, @Response() res): string {
    // res就变成空了,我想调用res.renderFile报错,把上面的ServeStaticModule去掉就正常
 
}

求教,试过直接在main.ts里直接对app进行设置静态目录,但是木有用,求教

@hongrunhui
Copy link
Author

我的需求是:
1、前端目录: dist/ 下放有使用webpack打包出来的前端页面
2、API接口: 提供给前端目录下的项目使用的接口,保证端口相同可以直接调用

@hongrunhui
Copy link
Author

已解决:
main.ts

import { NestFactory } from '@nestjs/core';
import { join } from 'path';
// import { renderFile } from 'ejs'
import { NestExpressApplication } from '@nestjs/platform-express';
// import { NestFastifyApplication, FastifyAdapter } from '@nestjs/platform-fastify';
import { AppModule } from './app.module';

async function bootstrap() {
    const app = await NestFactory.create<NestExpressApplication>(
        AppModule,
    );
    app.useStaticAssets(join(__dirname, '..', 'front-end/dist'));
    // app.setBaseViewsDir(join(__dirname, '..', 'views'));
    // app.setViewEngine('hbs');
    await app.listen(3000);
}
bootstrap();

@StormKid
Copy link

可以看我的博客 https://www.jianshu.com/p/d10134dae4cc

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants