【问题标题】:SSR Nuxt.js with integreted REST API backend带有集成 REST API 后端的 SSR Nuxt.js
【发布时间】:2020-08-18 22:47:20
【问题描述】:

我正在开发一个带有集成 REST API 服务器的 SSR Nuxt.js 应用程序。

为此,我在 Nuxt server.js 代码中添加了我的 /api 端点,如下所示

const express = require('express')
const consola = require('consola')
const { Nuxt, Builder } = require('nuxt')

const app = express()

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

// MY REST API ENDPOINT (It's the right approach?)
const routesApi = require('./api/routes')
app.use('/api', routesApi)

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

  const { host, port } = nuxt.options.server

  await nuxt.ready()
  // 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()

我没有找到与此方法相关的示例。

我需要一些帮助来了解它是否正确。

感谢您的支持。

【问题讨论】:

标签: node.js express vue.js nuxt.js


【解决方案1】:

您可能想阅读以下文章:https://blog.lichter.io/posts/nuxt-with-an-api/ 解决“API with Nuxt”的案例有共同点。

我猜,您的解决方案对于小型集成 API 来说已经足够了,这样您就可以避免针对 CORS 问题设置代理。 :) 你可以加点糖serverMiddleware:

// nuxt.config.js
export default {
...
  serverMiddleware: [
    '/api': '~/api/index.js'
  ],
...
}
// api/index.js
export default function (req, res, next) {
  ... // Well, here comes nothing
  next()
}

但是大型 API 在单独的服务器上可以很好地扩展,这也是要考虑的关注点分离。 Nuxt 可以更好地用作通用应用程序渲染中间件,但 API 甚至可以用另一种语言编写,后端。为了解决 CORS 的问题,您需要按照您的意愿将 /api 放在同一个域上,因此使用 Nuxt proxy-module 会更容易。

【讨论】:

    猜你喜欢
    • 2020-10-08
    • 1970-01-01
    • 2019-01-05
    • 2021-04-24
    • 2016-11-21
    • 2021-04-14
    • 1970-01-01
    • 1970-01-01
    • 2020-03-08
    相关资源
    最近更新 更多