首页 > 解决方案 > 我如何才能将下一个与嵌套集成?

问题描述

我试图next在自定义适配器函数的渲染中包含:

// custom.adapter.ts
import { ExpressAdapter } from '@nestjs/platform-express';
import { Response } from 'express';
import next  from 'next';

const dev = true;
const nextApp = next({ dev });
const handle = nextApp.getRequestHandler();

export class NextAdapter extends ExpressAdapter {
    constructor() { super() }
    
    render(res: Response, view: string, options: any) {
        const { req } = options;
        return new Promise<void>(async (resolve) => {
            nextApp.prepare().then(async () => {

                if (req.query = '/a') {
                    await nextApp.render(req, res, '/a', req.query)
                } else {
                    handle(req, res);
                }
                resolve();
            });
        });
    }
}

但这不起作用,我尝试获取页面并收到很多 404 错误。

// main.ts
import { NestFactory } from '@nestjs/core';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { AppModule } from './app.module';
import { NextAdapter } from './next.adapter';



async function bootstrap() {
  const app = await NestFactory.create(AppModule, new NextAdapter());

  const options = new DocumentBuilder()
    .setTitle('Blog Rest API dosc')
    .build();
  const document = SwaggerModule.createDocument(app, options);
  SwaggerModule.setup('api', app, document);

  await app.listen(3000);
}

bootstrap();

我在 github 上发布的所有代码 https://github.com/MiiZZo/nest-next/tree/master/nextapp
如果有人帮助我,我将不胜感激,谢谢!

标签: nestjsnext

解决方案


一种解决方案是使用nest-nexthttps ://www.npmjs.com/package/nest-next 详细文档在他们的页面上,但这里是相关代码,用于在嵌套 js 中包含下一个应用程序渲染:

import { Module } from '@nestjs/common';
import Next from 'next';
import { RenderModule } from 'nest-next';

@Module({
  imports: [
    RenderModule.forRootAsync(Next({ dev: process.env.NODE_ENV !== 'production' })),
    ...
  ],
  ...
})
export class AppModule {}

推荐阅读