Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Routes

A route connects an address and an HTTP method to the code that builds the response. All the application's routes are described in start/routes.ts — the file already exists in the project.

The first route

Open start/routes.ts and add a route at the end:

// start/routes.ts
import router from '@adonisjs/core/services/router'
 
router.get('/hello', async () => {
  return 'Hello!'
})

The router object is imported from the core package. The get method takes an address and a handler function. Open http://localhost:3333/hello — the page shows "Hello!".

What you can return

Whatever the handler returns becomes the response. A string is sent as text or HTML, and an object or array as JSON:

// start/routes.ts
router.get('/about', async () => {
  return '<h1>About the blog</h1>'
})
 
router.get('/api/status', async () => {
  return { status: 'ok', posts: 3 }
})

At /about the browser shows a heading, and at /api/status the JSON {"status":"ok","posts":3}. The framework sets the Content-Type header itself.

HTTP methods

Each request method has its own router method. One address can respond differently to different methods:

// start/routes.ts
router.get('/posts', async () => 'List of posts')
router.post('/posts', async () => 'Post created')
router.put('/posts/1', async () => 'Post updated')
router.delete('/posts/1', async () => 'Post deleted')
MethodWhat for
getShow a page or data
postCreate a record, submit a form
put, patchUpdate a record
deleteDelete a record
anyAny method

A template without a handler

If a page needs no code, only a template, use router.on:

// start/routes.ts
router.on('/').render('pages/home')

This route from the starter kit shows the template resources/views/pages/home.edge on the home page.

Listing routes

node ace list:routes

The command prints a table of all routes: method, address, name and handler. Handy when there are many routes.

Common mistake

You can open only a GET route in the browser: the address bar always sends GET. If you visit an address that has only router.post, you get a 404 error "Cannot GET:/posts". Test POST routes through a form or a tool like curl:

curl -X POST http://localhost:3333/posts

Thanks for reading!

Donate to the site — we work hard for you.