【问题标题】:Vue + Express app on heroku not using the SPA in server/public folderheroku 上的 Vue + Express 应用程序未使用服务器/公共文件夹中的 SPA
【发布时间】:2019-11-01 08:59:02
【问题描述】:

我的应用程序在 heroku 上运行,路由向我发送 JSON 文件,但我需要使用 ./server/public 文件夹中的 SPA 作为 index.html。 当我打开 heroku 应用程序时,它会向我发送从“/”路由发送的 JSON 文件,但我需要它来使用 Vue SPA,因为我在前端客户端中所做的事情,如果你出于某种原因去一个不存在的路由它会使用前端客户端将我重定向到我的“/forum”路由,但是任何其他存在的路由都将不起作用,它将继续发送该路由的 JSON。

app/server.js

const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const expressValidator = require("express-validator");
const flash = require('connect-flash');
const mongoose = require('mongoose');
const cors = require("cors");
const config = require("./config/database");
if(process.env.NODE_ENV !== "production") require('dotenv').config();

mongoose.connect(config.database, { useNewUrlParser: true, useFindAndModify: false });

let db = mongoose.connection;

db.once("open", () => {
    console.log("Connected to MongoDB Atlas");
});

db.on("error", (err) => {
    console.log(err);
});

const app = express();

//Body-parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use(cors());
app.use(expressValidator());
app.use(flash());
app.use(cors());

require("./passport")

//Routes
const home = require("./routes/home.js");
const forum = require('./routes/forum.js');
const ranking = require('./routes/ranking.js');
const profile = require('./routes/profile.js');

// Routing
app.use("/", home);
app.use("/forum", forum);
app.use("/profile", profile);
app.use("/ranking", ranking);

// Handle production build
if (process.env.NODE_ENV === "production") {
    app.use(express.static(__dirname + '/public/'));
    app.get(/.*/, (req, res) => { res.sendFile(__dirname + '/public/index.html') });
}

// PORT
const port = process.env.PORT || 3000;
app.listen(port, () => {
    console.log(`Server listening on port ${port}`)
});

【问题讨论】:

    标签: node.js express vue.js heroku


    【解决方案1】:

    如果您使用 Vue 和 Express 拆分前端和后端,您可能应该静态构建和托管 Vue 部分,然后让您的 Express 在 Heroku 上运行。

    Here 是关于如何部署 express 应用程序的指南,然后是构建和部署静态 Vue 页面,here 是部署 Vue 的文档。

    【讨论】:

    • 前端已经在我的快递应用程序中静态构建,只是没有发送它。例如,如果您转到主路由,它应该发送 index.html,但它发送的是控制器发送的 JSON。
    猜你喜欢
    • 1970-01-01
    • 2023-02-06
    • 2020-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-14
    • 1970-01-01
    相关资源
    最近更新 更多