BugBuddy
BugBuddy

Reputation: 606

How to add backend routes with hapi-nuxt in a Nuxt.js project?

I'm using hapi-nuxt in a javascript project similar to a Nuxt tutorial I am watching. I generated the skeleton app using:

npx create-nuxt-app <project-name>  

That gives me the following code in server/index.js:

const Hapi = require('hapi')
const consola = require('consola')
const HapiNuxt = require('hapi-nuxt')

const server = new Hapi.Server({
  host: process.env.HOST || 'localhost',
  port: process.env.PORT || 3000
})

server
  .register({
    plugin: HapiNuxt
  })
  .then(() => server.start())
  .then(() =>
    consola.ready({
      message: `Server running at: ${server.info.uri}`,
      badge: true
    })
  )
  .catch(err => {
    consola.error(err)
    throw err
  })

Now I want to add the routes listed in server/routes/index.js. I believe the code is similar to:

const routes = require('./routes');
...
routes.forEach(route => {
  app.route(route);
}

Assuming that code is correct, where do I put it?

Upvotes: 0

Views: 493

Answers (1)

Chung Nguyen
Chung Nguyen

Reputation: 501

Here is an example

// server/index.js

const consola = require('consola')
const Hapi = require('@hapi/hapi')
const HapiNuxt = require('@nuxtjs/hapi')
const Routes = require('./api')
async function start() {
  const server = new Hapi.Server({
    host: process.env.HOST || '127.0.0.1',
    port: process.env.PORT || 3000
  })

  await server.register({
    plugin: HapiNuxt,
    options: {}
  });

  await server.route(Routes);

  await server.start()

  consola.ready({
    message: `Server running at: ${server.info.uri}`,
    badge: true
  })
}

process.on('unhandledRejection', (error) => consola.error(error))

start()


// server/api/index.js

const route1 = {
  path: '/api',
  method: 'GET',
  handler (request, h) {
    return {
      works: true
    }
  }
}

module.exports = [
  route1
]

Upvotes: 1

Related Questions