项目的运行日志中出现了如下报错:
TypeError: ctx.i18n[(SET_PREFIX + key)] is not a function
at ctx.i18n.whitelist.some.key (/explorer/web-explore/node_modules/koa-i18n/index.js:107:59)
at Array.some (<anonymous>)
at i18nMiddleware (/explorer/web-explore/node_modules/koa-i18n/index.js:104:24)
at dispatch (/explorer/web-explore/node_modules/koa-compose/index.js:42:32)
at /explorer/web-explore/node_modules/koa-compose/index.js:34:12
at Application.handleRequest (/explorer/web-explore/node_modules/koa/lib/application.js:151:12)
at Server.handleRequest (/explorer/web-explore/node_modules/koa/lib/application.js:133:19)
at Server.emit (events.js:198:13)
at parserOnIncoming (_http_server.js:677:12)
at HTTPParser.parserOnHeadersComplete (_http_common.js:109:17)
这就导致了站点在部分浏览器如Firefox上会出现internet server error的问题。
定位到node_modules/koa-i18n/index.js文件中的107行:
return function i18nMiddleware(ctx, next) {
ctx.i18n.whitelist.some(key => {
const customLocaleMethod = typeof key === 'function'
&& ctx.i18n.setLocale(key.apply(ctx))
if (customLocaleMethod || ctx.i18n[SET_PREFIX + key]()) return true
})
return next()
}
使用类型判断typeof ctx.i18n[SET_PREFIX + key]()这个方法发现很多都是undefined也不想找了,直接try catch掉,改为如下代码:
return function i18nMiddleware(ctx, next) {
ctx.i18n.whitelist.some(key => {
const customLocaleMethod = typeof key === 'function'
&& ctx.i18n.setLocale(key.apply(ctx))
try{
if (customLocaleMethod || ctx.i18n[SET_PREFIX + key]()) return true
}catch(e){
}
//if (customLocaleMethod/* || ctx.i18n[SET_PREFIX + key]()*/) return true
})
return next()
}