0

自从我上次使用 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

服务器/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 上创建第二台服务器。

4

0 回答 0