gpt4 book ai didi

javascript - 如何处理 Koa 2 中的 404?

转载 作者:数据小太阳 更新时间:2023-10-29 04:11:20 33 4
gpt4 key购买 nike

我有一个 404.jade 文件,每当有无效的 GET 请求时我都想渲染它。

这是我当前的代码:

app.js

import Koa from 'koa'
import views from 'koa-views'
import serve from 'koa-static'
import rootRoutes from './routes/index'
import userRoutes from './routes/user'

const app = new Koa()

app.use(views(`${__dirname}/views`, { extension: 'jade' }))
app.use(serve(`${__dirname}/public`))
app.use(rootRoutes.routes())
app.use(userRoutes.routes())

app.listen(3000, () => {
console.log('Server running at http://localhost:3000')
})

export default app

routes/index.js

import Router from 'koa-router'
const router = new Router()

router.get('/', async ctx => {
await ctx.render('index')
})

router.get('/about', async ctx => {
await ctx.render('about')
})

export default router

routes/user.js

import Router from 'koa-router'
const router = new Router({ prefix: '/user' })

router.get('/:name', async ctx => {
const user = ctx.params.name
await ctx.render('user', { user })
})

export default router

我如何处理任何类型的无效 GET 请求并在其发生时以某种方式使用 await ctx.render('404')

最佳答案

您可以在app.js 文件中添加自定义中间件

import Koa from 'koa'
import views from 'koa-views'
import serve from 'koa-static'
import rootRoutes from './routes/index'
import userRoutes from './routes/user'

const app = new Koa()

app.use(async(ctx, next) => {
try {
await next()
const status = ctx.status || 404
if (status === 404) {
ctx.throw(404)
}
} catch (err) {
ctx.status = err.status || 500
if (ctx.status === 404) {
//Your 404.jade
await ctx.render('404')
} else {
//other_error jade
await ctx.render('other_error')
}
}
})

app.use(views(`${__dirname}/views`, { extension: 'jade' }))
app.use(serve(`${__dirname}/public`))
app.use(rootRoutes.routes())
app.use(userRoutes.routes())

app.listen(3000, () => {
console.log('Server running at http://localhost:3000')
})

export default app

关于javascript - 如何处理 Koa 2 中的 404?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37009352/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com