How to do it...

We'll start by creating a few files:

$ touch index.js
$ mkdir routes public
$ touch routes/index.js
$ touch public/styles.css

Now let's kick off the index.js file by loading necessary dependencies:

const Koa = require('koa') 
const serve = require('koa-static') 
const router = require('koa-router')() 
const {join} = require('path') 
const index = require('./routes/index') 

Next we'll create a Koa app and assign dev and port configuration references:

const app = new Koa() 
const dev = process.env.NODE_ENV !== 'production' 
const port = process.env.PORT || 3000 

Next we'll register relevant middleware and routes:

if (dev) { 
  app.use(serve(join(__dirname, 'public'))) 
} 
 
router.use('/', index.routes(), index) 
 
app.use(router.routes()) 

Finally, in index.js we'll bind Koa's internal server to our port by calling app.listen:

app.listen(port, () => { 
  console.log(`Server listening on port ${port}`) 
}) 

Our index.js file is relying on routes/index.js , so let's write it.

Our code in routes/index.js should look as follows:

const router = require('koa-router')() 
 
router.get('/', async function (ctx, next) { 
  await next() 
  const { title } = ctx.state 
  ctx.body = ` 
    <html> 
      <head> 
        <title> ${title} </title> 
        <link rel="stylesheet" href="styles.css"> 
      </head> 
      <body> 
        <h1> ${title} </h1> 
        <p> Welcome to ${title} </p> 
      </body> 
    </html> 
  ` 
}, async (ctx) => ctx.state = {title: 'Koa'}) 
 
module.exports = router 

Finally, the public/styles.css file:

body { 
  padding: 50px; 
  font: 14px "Lucida Grande", Helvetica, Arial, sans-serif; 
} 

Let's start our server with:

$ node index.js  

Access http://localhost:3000 in a browser, we should see something like the following screenshot:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset