2017-01-06 15 views
0

我有一個koa 2服務器。koa-static去下一個中間件

下面的代碼是我的中間件:

// parse body 
app.use(bodyParser()) 

// serve static 
app.use(serve(path.join(__dirname, '/public'))) 

// routes 
app.use(routes) 

// error middleware 
app.use(async ctx => ctx.throw(500)) 

一切都運行良好,但我的問題是,當我去本地主機:8000,在我的服務器生命,在控制檯中我看到了以下錯誤:

InternalServerError: Internal Server Error at Object.throw (/Users/work/Desktop/server/node_modules/koa/lib/context.js:91:23)

我懷疑靜態後,應用程序將轉到下一個中​​間件,這是錯誤中間件。

PS。我正在使用app.use(async ctx => ctx.throw(500)),如果我在其他路線上發生錯誤,請致電next()

有誰知道如何解決這個問題?

謝謝!

+0

你仍然有問題,如果你註釋掉錯誤中間件? – saadq

+0

沒有,但我需要的是 – Anderson

+0

好吧,只是確保這就是問題來自何處。你能分享你的'路線代碼? – saadq

回答

0

I'm suspecting that after static, the app is going to the next middleware, which is the error middleware.

koa-static通過設計將控制轉移到下一個中​​間件。 您的routes中間件也await到下一個中​​間件。 所以你得到一個錯誤。

Does anyone know how to fix this?

很難說你首先要做的是什麼。 手動設置500可能是一個錯誤的想法。應該有404這樣的:

// 404 middleware 
app.use(async ({response}, next) => { 
    if (!this.body) { 
    response.status = 404 
    response.body = "Not Found" // or use template 
    } 
    await next() // send control flow back (upstream) 
}) 

對於SPA(不含SSR),你可能想要這個包羅萬象的路線發送APP佈局來代替。並移動404中間件的文件的開頭(其中將採取的第二個「冒泡」相位控制。

請務必檢查this

0

使用一樣,你添加一箇中間件來處理您的自定義錯誤正確...

// serve static 
app.use(serve(path.join(__dirname, '/public'))) 
// error middleware 
app.use(async(ctx, next) => { 
    try { 
     await next(); 
    } catch (e) { 
     console.log(e.message); 
     ctx.body = e.message 
    } finally {} 
}) 
// routes 
app.use(router.routes()).use(router.allowedMethods()); 

router.get('/a', ctx => { 
    try { 
     ctx.body = "sadsa" 
    } catch (e) { 
     ctx.body = e 
     console.log(e); 
    } finally {} 
}); 
app.use(ctx => ctx.throw(500)) 
app.listen(7000) 
+0

你會介意解釋你是什麼與OP的做法和原因有所不同。總是有一個教學時刻,並且會幫助其他人遇到可能有微妙差別的問題。 –