【问题标题】:Nuxt & Express server not getting api requests in production /distNuxt 和 Express 服务器在生产 /dist 中没有收到 api 请求
【发布时间】:2022-06-11 21:41:38
【问题描述】:

我有一个 Nuxt 应用程序在我的本地服务器上成功运行,并且所有 API 请求都在同一台服务器上成功运行(使用 nuxt.config.js 中的 serverMiddleware 属性)。当我运行yarn generate 时,API 服务器的路径丢失并且没有加载数据。下面是几张截图。

从 API 成功加载数据。

找不到 API

这里是 project_dir api/index.js 文件中的 api 调用示例

const express = require("express");
const passport = require("passport");
const allRoutes = require("../api/routes/routes");
const guestRoutes = require("../api/routes/guest");
const fileUpload = require("express-fileupload");
const path = require("path");

// Create express instance
const app = express();
// Init body-parser options (inbuilt with express)
app.use(express.json());
app.use(fileUpload());
app.use(express.urlencoded({ extended: false }));

app.use(express.static(path.join(__dirname, "../", "dist")));

/**
 * -------------- PASSPORT AUTHENTICATION ----------------
 */

// Need to require the entire Passport config module so index.js knows about it
require("./config/passport-jwt");

// Initialize Passport
app.use(passport.initialize());

/**
 * -------------- ROUTES ----------------
 */

// Imports all of the routes from ./routes/index.js
app.use(guestRoutes);
app.use(passport.authenticate("jwt", { session: false }), allRoutes);

console.log("express");
console.log(path.join(__dirname, "../", "dist"));


app.get("*", (req, res) => {
  res.sendFile(path.join(__dirname, "../", "dist", "index.html"));
});

// Export express app
module.exports = app;

我不知道为什么我无法从我在同一台服务器上运行的 API 路由获取数据。

【问题讨论】:

    标签: javascript node.js express nuxt.js


    【解决方案1】:

    下面是关于如何在 Nuxt 旁边运行 Express 服务器的深入解答:https://stackoverflow.com/a/72102209/8816585

    首先要知道的是,你不能有一个带有yarn generate 的 Node.js 服务器,因为它使用的是 target: 'static',你可以猜到,当某些东西是静态的时,它不需要 Node.js 服务器来提供给最终用户(只有 html + css + js static 文件托管在 CDN 或类似网站上)。
    此模式旨在将代码托管在 Netlify、Vercel 或类似平台上,而那里没有可用的 Node.js 服务器。

    为什么它在本地工作?因为您确实有一个 Webpack 开发服务器正在运行(使用 Node.js 服务器),用于调试目的,如 HMR 等......


    TDLR:这是正常的(目前按预期工作)。有关如何使其工作的更多信息,请参见上面的给定链接。

    【讨论】:

    • 我使用 target static 因为我想将它捆绑到桌面应用程序中。
    • @Divine 你不能在静态模式下运行 Node.js 服务器。不知道它与桌面应用程序有什么关系。
    • 我正在使用 nuxtron 包构建项目以供桌面使用。打包项目时,默认运行 npm run generate 。这就是为什么我想知道是否有一种方法可以在静态模式下访问 API。
    • @Divine 我的回答和之前的评论仍然有效。
    【解决方案2】:

    经过大量研究和调试,我想出了一个新想法。 而不是在 package.json 文件中运行包含脚本 "nuxt start"npm run startyarn start。我添加了一个名为 "express-start": "cross-env NODE_ENV=production node api/index.js" 的新脚本。它运行 express 服务器和 nuxt 静态文件。 我目前正在创建一个模板,以便那些将面临这一挑战的人更容易。

    链接到我在解决问题后创建的样板。 ExpressJs & NuxtJs Boilerplate

    【讨论】:

    • 我使用 ExpressJS、NuxtJS 和 ElectronJS 构建了这个项目。
    猜你喜欢
    • 1970-01-01
    • 2015-05-23
    • 1970-01-01
    • 2019-08-02
    • 1970-01-01
    • 2018-08-26
    • 1970-01-01
    • 2019-03-23
    • 1970-01-01
    相关资源
    最近更新 更多