gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 12:18:42 25 4
gpt4 key购买 nike

我正在开发一个带有集成 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com