typestack / routing-controllers

Create structured, declarative and beautifully organized class-based controllers with heavy decorators usage in Express / Koa using TypeScript and Routing Controllers Framework.
MIT License
4.39k stars 391 forks source link

【BUG】koa render will break all API request #610

Open Gcaufy opened 3 years ago

Gcaufy commented 3 years ago

When use @Render in Koa, it will break all api request, all API request will return a html template.

How to produce

  1. Create a html render controller

    // html/default.ts
    @Controller()
    export default class DefaultController {
    @Get('/homepage')
    @Render('home/index')
    async index() {
    return {
      title: config.app.name,
    };
    }
    }
  2. Create a api json controller

    // api/default.ts
    @JsonController()
    export default class DefaultController {
    @Get("/api/users")
    getAll() {
    return {
      code: 0,
      data: [{ name: 'Jim Green', id: 1 }]
    };
    }
  3. Test

    curl http://localhost/api/users    // show json as expected
    curl http://localhost/homepage   // show HTML page as expected
    curl http://localhost/api/users    // show HTML page (!!NOT EXPECTED!!)

Reason code

https://github.com/typestack/routing-controllers/blob/24556885e58e1022531881eecb963c363e9933a9/src/driver/koa/KoaDriver.ts#L245-L251

in KoaDriver.ts, handleSuccess will register a render middleware. so that every request will goes to the middleware, even a JSON api.

beclass commented 5 months ago

Has this not been updated to the main branch yet? Now, after each installation, it is necessary to modify this file separately