Skip to content

Controller for API and non-API route at the same time? #1270

Answered by popovicieduard
fishnux asked this question in Help
Discussion options

You must be logged in to vote

I think you can create a controller for both routes and return view or json response based on the header content-type or custom key, you could also add a middleware for your api routes that adds a header key.

https://preview.adonisjs.com/guides/http/content-negotiation

import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'

export default class PostsController {
  public async index ({ request, view }: HttpContextContract) {
    const posts = [{
      title: 'Adonis 101',
    }]

    switch (request.accepts(['html', 'json'])) {
      case 'html':
        return view.render('posts/index', { posts })
      case 'json':
        return posts
      default:
        return view.rend…

Replies: 3 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by fishnux
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Help
Labels
None yet
3 participants