zoukankan      html  css  js  c++  java
  • 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();
      }
    
  • 相关阅读:
    事后诸葛亮
    冲刺总结
    Alpha第十天
    Alpha第八天
    Alpha第九天
    Alpha第六天
    Alpha第七天
    Alpha第五天
    Python之pytesseract模块-实现OCR
    Selenium4 IDE初体验
  • 原文地址:https://www.cnblogs.com/ajanuw/p/9574535.html
Copyright © 2011-2022 走看看