Nestjs 设置静态文件,public

Docs: https://docs.nestjs.com/techniques/mvc

新版本需要设置为NestExpressApplication

import { NestExpressApplication } from '@nestjs/platform-express';

const app = await NestFactory.create<NestExpressApplication>(AppModule);
app.setBaseViewsDir(join(__dirname, '..', 'views'));
...

main.js

import {
  NestFactory
} from '@nestjs/core';

import {
  AppModule
} from './app.module';

import { join } from 'path'

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  // app.useStaticAssets(join(__dirname, '..', 'public'))  // http://localhost:5000/xxx.txt
  // app.useStaticAssets('public')  跟上面一样
   app.useStaticAssets(join(__dirname, '..', 'public'),{
    prefix: '/static/', 设置虚拟路径
  }) // http://localhost:5000/static/xxx.txt
   await app.listen(5000);
}
bootstrap();

加载静态页面

yarn add ejs

import {
  NestFactory
} from '@nestjs/core'

import {
  AppModule
} from './app.module'

import {
  join
} from 'path'
import {
  renderFile
} from 'ejs'

const l = console.log


async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useStaticAssets(join(__dirname, '..', 'public'), {
    prefix: '/static/'
  })

  app.setBaseViewsDir(join(__dirname, '..', 'views')) // 放视图的文件
  app.engine('html', renderFile);
  app.set('view engine', 'html');

  await app.listen(5000)
}
bootstrap();


  @Get()
  @Render('index')  // 使用render渲染 /views/index.hmtl 文件
  root() { }

sendFile

  @Get()
  root(@Response() res): any {
    res.sendFile(join(__dirname, '../view/', 'index.html'))
    // return this.appService.root();
  }
posted @ 2018-09-02 17:35  Ajanuw  阅读(5055)  评论(0编辑  收藏  举报