node.js - 带有集成 REST API 后端的 SSR Nuxt.js

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

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

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

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()

我没有找到与这种方法相关的例子。

我需要一些帮助来了解这是否是正确的方法。

感谢您的支持。

最佳答案

您可能想阅读以下文章: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 更容易.

关于node.js - 带有集成 REST API 后端的 SSR Nuxt.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61593418/

相关文章:

node.js - 将配置传递给 Controller

vue.js - vue.config.js 中的 Vue devServer.proxy 不工作

node.js - 使用 AWS 的动态网站

javascript - 存储带有多个彼此相邻的撇号的字符串

Node.js TLS "TypeError: Cannot read property ' indexOf' 未定义”

express - 如何在 Jest 中测试 Express 中间件的 `verify`

javascript - 在 Node.js 中从 JSON 导入数据库中的数据

node.js - Docker 主机名未在 next.js prod 中解析但在开发模式下工作(错误 : getaddrinfo ENOTFOUND)

reactjs - 组织数百个组件的最佳实践?

javascript - 如何在Vue中的组件之间共享一些代码