如何使用Fastify和Nuxt创建api路由?

时间:2019-07-10 03:27:46

标签: javascript nuxt.js fastify

Fastify自从我上一次玩以来变化很大。另外,我读到我们应该使用Nuxt serverMiddleware 添加api路由,但是我找不到任何有关如何进行操作的示例。

下面是我的索引文件,用于启动Fastify。我尝试在nuxt之前使用以下代码在其中添加路由:

fastify.register(require('./routesIndex'), { prefix: '/api' })

routesIndex.js ,根据新的fastify文档:

async function routes(fastify, options) {
    fastify.register(require('./fetchRemote'))
    fastify.register(require('./domains'))
}

module.exports = routes

要彻底,请 domains.js 文件:

async function routes(fastify, options) {
    const database = fastify.mongo.db('db')
    const collection = database.collection('test')

    fastify.get('/domains/list', async (request, reply) => {
        return { hello: 'world' }
    })

    fastify.get('/domains/:id', async (request, reply) => {
        const result = await collection.findOne({ id: request.params.id })
        if (result.value === null) {
            throw new Error('Invalid value')
        }
        return result.value
    })
}

module.exports = routes

server / index.js

const { Nuxt, Builder } = require('nuxt')
const fastify = require('fastify')({
  logger: true
})

fastify.register(require('./db'), {
  url: 'mongodb://localhost:27017'
})

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

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

  const {
    host = process.env.HOST || '127.0.0.1',
    port = process.env.PORT || 3000
  } = nuxt.options.server

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

  fastify.use(nuxt.render)

  fastify.listen(port, host, (err, address) => {
    if (err) {
      fastify.log.error(err)
      process.exit(1)
    }
  })
}

start()
在浏览器中找不到

/ api 路由。但后来我读到我应该在 nuxt.config.js 中使用serverMiddleware:

serverMiddleware: [
    { path: '/api', handler: '~/server/routesIndex.js' },
  ],

这样做会导致 fastify.register 出现错误:

(node:10441) UnhandledPromiseRejectionWarning: TypeError: fastify.register is not a function
    at routes (/media/srv/testingNuxt/server/routesIndex.js:4:13)
    at call (/media/srv/testingNuxt/node_modules/connect/index.js:239:7)
    at next (/media/srv/testingNuxt/node_modules/connect/index.js:183:5)
    at next (/media/srv/testingNuxt/node_modules/connect/index.js:161:14)
    at WebpackBundler.middleware (/media/srv/testingNuxt/node_modules/@nuxt/webpack/dist/webpack.js:5430:5)
(node:10441) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:10441) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

如何使用Fastify和Nuxt添加api路由? 我想避免仅在api上在端口3001上创建第二台服务器。

0 个答案:

没有答案