Adonis 入门 —— 请求

查询参数query & params

Route.get('/posts', ({ request }) => {
    return request.get()
})

使用post 请求

Route.post('/posts', ({ request }) => request.post())

同时得到请求地址的参数,使用request.all()

Route.post('/posts', ({ request }) => request.all())

获取指定参数,使用request.only()

Route.post('/posts', ({ request }) => request.only(['title', 'content']))

排除数据,使用request.except()

Route.post('/posts', ({ request }) => request.except(['title', 'content']))

获取指定参数,使用request.input()

Route.post('/posts', ({ request }) => request.input('status', '默认'))

Form 表单数据

{
  "title": [
    "Lemon",
    "Bnanna"
  ],
  "content": [
    "🍋",
    "🍌"
  ]
}
Route.post('/posts', ({ request }) => request.collet(['title', 'content']))

自动转换,使用request.collect

Route.post('/posts', ({ request }) => request.collect(['title', 'content']))

获取所有头部信息

Route.get('/posts', ({ request }) => request.headers())

获取指定信息

Route.get('/posts', ({ request }) => request.header('user-agent'))

设置响应头部信息

Route.get('/posts', ({ request, response }) => {
    // response.header('Content-type', 'text/plain')
    // 简写
    response.type('text')
    return '<h1>List of posts.</h1>'
})

Cookies 设置与获取

Route.get('/posts', ({ request, response }) => {
    // 设置cookie
    response.cookie('theme', 'dark')
    // 获取cookie
    // request.cookie('theme', '默认')
    // 删除cookie
    response.clearCookie('theme')
    return request.cookies()
})

Response 响应

Route.get('/posts', ({ response }) => {
    // response.send('List of response')
    // return 'List of return.'
    // 会自动将对象和组数转换成JSON
    return {
        'title': 'hello'
    }
})

异步响应

const delay = (data, time) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(data)
        }, time);
    })
}
Route.get('/posts', async ({ response }) => {
    const data = await delay('List of Posts.', 3000)
    return data
})

重定向 Redirects

Route.get('/list-of-posts', ({ response }) => {
    // response.redirect('/posts', true, 301)
    response.route('list-of-posts')
})

Route.get('/list-of-food-posts', ({ response }) => {
    // response.redirect('/posts', true, 301)
    response.route('list-of-posts', {
      category: 'food'
    })
})

Route.get('/posts/:category?', ({ params }) => {
    return `List of ${ params.category || 'default' } Posts.`
}).as('list-of-posts')

完整源码

说点什么

avatar
  Subscribe  
提醒