Ste*_*ldi 4 node.js express vue.js nuxt.js
我正在开发一个带有集成 REST API 服务器的 SSR Nuxt.js 应用程序。
为此,我/api在 Nuxtserver.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()
Run Code Online (Sandbox Code Playgroud)
我没有找到与此方法相关的示例。
我需要一些帮助来了解这是否是正确的方法。
感谢您的支持。
您可能想阅读以下文章: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'
],
...
}
Run Code Online (Sandbox Code Playgroud)
// api/index.js
export default function (req, res, next) {
... // Well, here comes nothing
next()
}
Run Code Online (Sandbox Code Playgroud)
但是大型 API 在单独的服务器上可以很好地扩展,这也是需要考虑的关注点分离。Nuxt 更适合作为通用应用程序渲染中间件,但 API 甚至可以用另一种语言(后端)编写。为了解决 CORS 的问题,您需要按照您的预期放置在同一域上,因此使用Nuxt proxy-module/api更容易。
| 归档时间: |
|
| 查看次数: |
12658 次 |
| 最近记录: |