0

Below is the simple Koa server that I have setup. However, every time when an invalid GET request is performed, the server "hangs", as in the network resource tab in Chrome would specify pending.

server.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)}`);
    }
});

Error Middleware

export default async function errorHandler(ctx, next) {
    try {
        await next();
    } catch (err) {
        console.log(pe.render(err));
        ctx.redirect('/oops');
    }
}

How can I gracefully handle all invalid GET request ?, including invalid static file requests ?

gevorg
  • 4,835
  • 4
  • 35
  • 52
cusX
  • 470
  • 1
  • 6
  • 17

1 Answers1

1

By using app.use(router.allowedMethods()) middleware.

You can define the response method of notImplemented or methodNotAllowed by yourself.

Joey
  • 446
  • 6
  • 11