简体   繁体   English

带生成的 Nuxt 服务器中间件

[英]Nuxt server middleware with generate

I think i'm misunderstanding nuxt server middleware.我想我误解了 nuxt 服务器中间件。 I have an api directory with a single file that spins up express and writes records to a mysql database.我有一个 api 目录,其中包含一个文件,该文件启动 express 并将记录写入 mysql 数据库。 Everything works as expected running in dev, but after nuxt generate, that endpoint always returns a 404.一切都按预期在 dev 中运行,但在 nuxt 生成之后,该端点总是返回 404。

Can you use nuxt generate with an internal API that runs on the server?您可以将 nuxt generate 与在服务器上运行的内部 API 一起使用吗? I'd be using axios to hit this endpoint for what it's worth but I doubt that makes a difference.我会使用 axios 来达到这个端点的价值,但我怀疑这会有所作为。

from Nuxt config:从 Nuxt 配置:

{
  target: static, 
  serverMiddleware: [{ path: '/api', handler: '~/api/index.js' }]
}

Server middleware basically allows you to run your own code on the server nuxt spins up for you in target: 'server' mode.服务器中间件基本上允许您在服务器上运行您自己的代码 nuxt 在target: 'server'模式下为您启动。 Therefore your approach won't work in static mode, as there is no server running your middleware.因此,您的方法在 static 模式下不起作用,因为没有服务器运行您的中间件。 You are only serving static files.您只提供 static 文件。 In dev mode you are running a server locally, which is why your middleware works fine there.在开发模式下,您在本地运行服务器,这就是您的中间件在那里正常工作的原因。

For it to work in production you have two options:要使其在生产中工作,您有两种选择:

  • Run nuxt in target: 'server' mode, instead of generating static filestarget: 'server'模式下运行 nuxt,而不是生成 static 文件
  • Spin up your express server separately, instead of using server middleware in nuxt单独启动您的 express 服务器,而不是在 nuxt 中使用服务器中间件

I hope you understand how server middleware works now and you can make the right decision for your project!我希望您现在了解服务器中间件的工作原理,并且可以为您的项目做出正确的决定!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM