All aboard the Koa train to servertown!
Okay, let's get into the nitty-gritty right away, and I'll explain what's going on. Add all of this into a new file in lib/chapter8
called index.js
:
import * as Koa from 'koa'; import * as bodyParser from 'koa-bodyparser'; const app = new Koa(); const port = process.env.PORT || 5555; app.use(bodyParser()); app.listen(port, () => console.log(`Listening on port ${port}`)); export default app;
Here, we import Koa and Koa Body Parser, instantiate Koa, assign a port number (defaulting to 5555
), tell Koa to use the Body Parser middleware (which mainly just interprets POST
request bodies into JavaScript objects for us) and then tell Koa to listen on that port.
What is process.env.PORT
? The process.env
is simply a global object of all environment variables from the shell that spawned the NodeJS script. We listen for requests on either port 5555 or whatever the PORT
environment variable is set to. I've emphasized that last line because it...