我正在开发一个带有集成REST服务器的SSR Nuxt.js应用程序。
为此,我在Nuxt server.js代码中添加了我的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()我没有找到与这种方法相关的例子。
我需要一些帮助来理解这是否是正确的方法。
谢谢您一直鼓励我。
发布于 2020-05-15 18:07:57
您可能希望阅读以下文章:https://blog.lichter.io/posts/nuxt-with-an-api/ --解决"API“的常见方法。
您的解决方案对于小型集成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代理模块就更容易了。
https://stackoverflow.com/questions/61593418
复制相似问题