【问题标题】:How to use Express with Vue如何在 Vue 中使用 Express
【发布时间】:2020-04-09 05:54:24
【问题描述】:

第一次使用 Node js、Express 和 Vue。

我有一个用 vue(不是 vue-app/vue-cli)制作的番茄钟网站,我想上传到 Heroku。该网站在本地使用 Webstorm IDE 可以完美运行,但无法使其与 Express 一起使用。

项目的Github链接:https://github.com/marcelmiro/Pomodoro

这是我的文件的组织方式:

+-- node_modules
  -- vue & express modules
+-- scripts
  -- main.css
  -- main.js (where my vue code is)
  -- bundle.js (me testing how to use a webpack. its not being used atm)
+-- assets
  -- all images
+-- index.html
+-- package.json
+-- Procfile
+-- server.js

server.js:

const express = require('express');
const app = express();
const port = process.env.PORT || 8080;

app.use("/scripts", express.static("scripts"));

app.get('/', (req, res) => res.sendFile(__dirname + "/index.html"));

app.listen(port, () => {
    console.log('Server connected at:',port);
});

所以我可以设法加载 css(虽然不是所有 css 代码),但不能加载 main.js(我的 vue 代码所在的位置)。图片也没有加载。

我该如何解决这个问题?

【问题讨论】:

    标签: node.js express vue.js heroku npm


    【解决方案1】:

    因为index.html在你的根目录下,你只需要告诉express去那里看;

    const express = require('express');
    const app = express();
    const port = process.env.PORT || 8080;
    
    app.use('/', express.static(__dirname));
    
    app.listen(port, () => {
        console.log('Server connected at:',port);
    });
    

    实际上,您可能希望将源代码与生产代码分开,但这有点超出了这个问题的范围。

    【讨论】:

    • 所以我应该替换“app.use('/', express.static(__dirname));”对于“app.use("/scripts", express.static("scripts"));" ?
    • 不,完全按照上面的说明使用它。您的脚本文件夹是相对于 index.html 的,所以当您点击“/”(即任何路线)时,您对 Express 说,服务 index.html
    • 非常感谢!有效!顺便说一句,您说我应该将源代码和生产代码分开是什么意思?
    • 没问题。单独的 src 和 dist 文件夹 - 因此当您准备好部署时,您的生产就绪代码被捆绑到“dist”中。它非常复杂,因此我建议您遵循教程:youtube.com/watch?v=j55fHUJqtyw
    猜你喜欢
    • 1970-01-01
    • 2019-07-18
    • 1970-01-01
    • 2021-01-10
    • 1970-01-01
    • 2020-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多