下面是我设置的简单 Koa 服务器。但是,每次执行无效的 GET 请求时,服务器都会“挂起”,因为在 Chrome 的网络资源选项卡中会指定pending。
服务器.js
const app = new Koa();
const apiUrl = `http://${KOA_HOST}:${API_PORT}`;
const proxy = httpProxy.createProxyServer({
target: apiUrl,
});
const router = new Router();
app.use(errorHandler);
app.use(compress({
flush: zlib.Z_SYNC_FLUSH,
}));
app.use(responseTime());
app.use(logger());
app.use(helmet());
app.use(bodyParser());
router.get('/bundle/*', serveStatic(PUBLIC_PATH));
router.get('*', render);
app.use(router.routes());
const server = http.createServer((req, res) => {
const path = url.parse(req.url).pathname;
if (/^\/api.*/.test(path)) {
return proxy.web(req, res, { target: apiUrl });
}
app.callback()(req, res); // need to understand this more
});
server.listen(KOA_PORT, KOA_HOST, err => {
if (err) {
console.log(chalk.red(err));
} else {
const url = `http://${KOA_HOST}:${KOA_PORT}`;
console.log(`${chalk.yellow(`backend server`)} listening on ${chalk.yellow(url)}`);
}
});
错误中间件
export default async function errorHandler(ctx, next) {
try {
await next();
} catch (err) {
console.log(pe.render(err));
ctx.redirect('/oops');
}
}
如何优雅地处理所有无效的 GET 请求?包括无效的静态文件请求?