diff --git a/index.js b/index.js index 1f51b1771..a63ed2cb6 100644 --- a/index.js +++ b/index.js @@ -5,6 +5,7 @@ const config = require('./config'); const onerror = require('./middleware/onerror'); const header = require('./middleware/header.js'); +const utf8 = require('./middleware/utf8'); const memoryCache = require('./middleware/cache.js'); const redisCache = require('koa-redis-cache'); @@ -24,22 +25,28 @@ app.use(onerror); // set header app.use(header); +// fix incorrect `utf-8` characters +app.use(utf8); + // cache if (config.cacheType === 'memory') { - app.use(memoryCache({ - expire: config.cacheExpire - })); -} -else if (config.cacheType === 'redis') { - app.use(redisCache({ - expire: config.cacheExpire, - onerror: (e) => { - logger.error('cache error', e); - } - })); + app.use( + memoryCache({ + expire: config.cacheExpire + }) + ); +} else if (config.cacheType === 'redis') { + app.use( + redisCache({ + expire: config.cacheExpire, + onerror: (e) => { + logger.error('cache error', e); + } + }) + ); } // router app.use(router.routes()).use(router.allowedMethods()); -app.listen(config.port); \ No newline at end of file +app.listen(config.port); diff --git a/middleware/utf8.js b/middleware/utf8.js new file mode 100644 index 000000000..cca1a34a8 --- /dev/null +++ b/middleware/utf8.js @@ -0,0 +1,6 @@ +// https://stackoverflow.com/questions/2507608/error-input-is-not-proper-utf-8-indicate-encoding-using-phps-simplexml-lo/40552083#40552083 +// https://stackoverflow.com/questions/1497885/remove-control-characters-from-php-string/1497928#1497928 +module.exports = async (ctx, next) => { + await next(); + ctx.body = ctx.body.replace(/[\x00-\x1F\x7F]/g, ''); +};