user9801251
user9801251

Reputation:

Include api routes in a nuxt and express app (using create-nuxt-app)

I created an app using the create-nuxt-app npm command and I got this server/index.js file.

const express = require('express')
const consola = require('consola')
const { Nuxt, Builder } = require('nuxt')
const app = express()
const host = process.env.HOST || '127.0.0.1'
const port = process.env.PORT || 3000

app.set('port', port)

// Import and Set Nuxt.js options
let config = require('../nuxt.config.js')
config.dev = !(process.env.NODE_ENV === 'production')

async function start() {
  // Init Nuxt.js
  const nuxt = new Nuxt(config)

  // Build only in dev mode
  if (config.dev) {
    const builder = new Builder(nuxt)
    await builder.build()
  }

  // Give nuxt middleware to express
  app.use(nuxt.render)

  // Listen the server
  app.listen(port, host)
  consola.ready({
    message: `Server listening on http://${host}:${port}`,
    badge: true
  })
}
start()

I also have a js file containing my api routes.

const { Router } = require('express')
const router = Router()
router.get('/route1', function(req, res){
   return 'Hello world';
}
module.exports = router

I am looking for a way to prefix the routes with 'api', without adding it to each route one by one (if possible) as well as including the routes in the first place.

Upvotes: 2

Views: 5257

Answers (3)

Mohammed Ibrahim
Mohammed Ibrahim

Reputation: 1

you can add in server/index.js file.

app.use(nuxt.render)

Upvotes: 0

Efrén
Efrén

Reputation: 435

According to the documentation:

https://nuxtjs.org/api/configuration-servermiddleware/

https://nuxtjs.org/examples/auth-routes

API routes apply to nuxt.config.js

serverMiddleware: [
    '~/api'
],

It works for me.

Upvotes: 1

William Chong
William Chong

Reputation: 2203

Just apply your api route as middleware with prefix path

import api from './api';
app.use('/api', api);

Ref: https://expressjs.com/en/api.html#path-examples

Upvotes: 2

Related Questions