如何通过NuxtJs项目在Express API中传递参数?

问题描述 投票:0回答:1

我正在构建具有以下选项的项目NuxtJs + ExpressJs(SSR类型)>>

enter image description here

在文件server/index.js中,我导入API路由

const express = require('express')
const consola = require('consola')
const { Nuxt, Builder } = require('nuxt')
const app = express()
const fs = require('fs')
const api = require("./routes/routes.js")(app, fs);

// Import API route
app.use('/api', api);
// Import and Set Nuxt.js options
const config = require('../nuxt.config.js')
config.dev = process.env.NODE_ENV !== 'production'

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

routes/routes.js

// import other routes
const productRoutes = require("./product/products.js");

const appRouter = (app, fs) => {
  // default route
  app.get("/", (req, res) => {
    res.send("welcome to the development api-server");
  });

  // // other routes
  productRoutes(app, fs);
};

module.exports = appRouter;

并且在product/products.js

const productRoutes = (app, fs) => {
    app.get("/products", (req, res) => {});
    app.post("/products", (req, res) => {});
    app.put("/products/:id", (req, res) => {});
    app.delete("/products/:id", (req, res) => {});
};
module.exports = productRoutes;

但是,我有错误TypeError: app.use() requires a middleware function。也许我在使用(app, fs)时无法传递参数app.use('/api', api),并且需要处理中间件。我是ExpressJs和Middleware的新手。我不知道我在想什么。我希望有人能给我解决方案。非常感谢。

我使用以下选项构建项目NuxtJs + ExpressJs(SSR类型)在文件server / index.js中,我导入了API路由const const express = require('express')const consola = require('consola')const {...

express vue.js nuxt.js middleware
1个回答
0
投票
const { loadNuxt, build } = require('nuxt')
const express = require('express')
const consola = require('consola')
const bodyParser = require('body-parser')
const app = express()
const fs = require('fs')

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

//Import routes
const api = require("./routes/routes.js")(app, fs);

app.use('/api', api);


const isDev = process.env.NODE_ENV !== 'production'
const port = process.env.PORT || 3000

async function start() {
  // We get Nuxt instance
  const nuxt = await loadNuxt(isDev ? 'dev' : 'start')

  // Render every route with Nuxt.js
  app.use(nuxt.render)

  // Build only in dev mode with hot-reloading
  if (isDev) {
    build(nuxt)
  }
  // Listen the server
  app.listen(port, '0.0.0.0')
  console.log('Server listening on `localhost:' + port + '`.')
}

start()
© www.soinside.com 2019 - 2024. All rights reserved.