首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带有集成REST后端的SSR Nuxt.js

带有集成REST后端的SSR Nuxt.js
EN

Stack Overflow用户
提问于 2020-05-04 13:30:13
回答 1查看 10.2K关注 0票数 4

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

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

代码语言:javascript
复制
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()

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

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

谢谢您一直鼓励我。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-15 18:07:57

您可能希望阅读以下文章:https://blog.lichter.io/posts/nuxt-with-an-api/ --解决"API“的常见方法。

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

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

但是大API在单独的服务器上扩展得很好,它也是一个需要考虑的关注点的分离。Nuxt作为通用的应用程序呈现中间件提供了更好的服务,但是API甚至可以用另一种语言后端编写。为了克服CORS的问题,您需要将/api放在您想要的相同域上,这样使用Nuxt代理模块就更容易了。

票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61593418

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档