routing-controllers icon indicating copy to clipboard operation
routing-controllers copied to clipboard

【BUG】koa render will break all API request

Open Gcaufy opened this issue 3 years ago • 1 comments

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,
    };
  }
}
  1. 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 }]
    };
  }
  1. 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.

Gcaufy avatar Nov 10 '20 09:11 Gcaufy