index.js
This file
Path
examples/basic/index.js
104 lines 路 2.4 KiB 路 JavaScript
Last changed by
refactor: refactor something (#65)Yusuke Wadabefore adoption336afc8
History of this fileTake it
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105import { Hono, Middleware } from '../../dist'// or install from npm:// import { Hono, Middleware } from 'hono'
const app = new Hono()
// Mount Builtin Middlewareapp.use('*', Middleware.poweredBy())app.use('*', Middleware.logger())app.use('/form', Middleware.bodyParse())app.use( '/auth/*', Middleware.basicAuth({ username: 'hono', password: 'acoolproject', }))
// Custom Middleware// Add Custom Headerapp.use('/hello/*', async (c, next) => { await next() await c.res.headers.append('X-message', 'This is addHeader middleware!')})
// Log response timeapp.use('*', async (c, next) => { await next() const responseTime = await c.res.headers.get('X-Response-Time') console.log(`X-Response-Time: ${responseTime}`)})
// Add X-Response-Time headerapp.use('*', async (c, next) => { const start = Date.now() await next() const ms = Date.now() - start await c.res.headers.append('X-Response-Time', `${ms}ms`)})
// Handle errorapp.use('*', async (c, next) => { try { await next() } catch (err) { console.error(`${err}`) c.res = new Response('Custom Error Message', { status: 500 }) }})
// Routingapp.get('/', (c) => c.text('Hono!!'))// Use Response object directlyapp.get('/hello', () => new Response('This is /hello'))
// Named parameterapp.get('/entry/:id', (c) => { const id = c.req.param('id') return c.text(`Your ID is ${id}`)})// Redirectapp.get('/redirect', (c) => c.redirect('/'))// Authentication requiredapp.get('/auth/*', (c) => c.text('You are authorized'))
// Asyncapp.get('/fetch-url', async (c) => { const response = await fetch('https://example.com/') return c.text(`https://example.com/ is ${response.status}`)})
// Request headersapp.get('/user-agent', (c) => { const userAgent = c.req.header('User-Agent') return c.text(`Your UserAgent is ${userAgent}`)})
// JSONapp.get('/api/posts', (c) => { const posts = [ { id: 1, title: 'Good Morning' }, { id: 2, title: 'Good Aternoon' }, { id: 3, title: 'Good Evening' }, { id: 4, title: 'Good Night' }, ] return c.json(posts)})// status codeapp.post('/api/posts', (c) => c.json({ message: 'Created!' }, 201))// default routeapp.get('/api/*', (c) => c.text('API endpoint is not found', 404))
app.post('/form', async (c) => { return c.json(c.req.parsedBody || {}) //return new Response('ok /form')})
// Throw Errorapp.get('/error', () => { throw Error('Error has occurred')})
// addEventListenerapp.fire()