【问题标题】:Deploying Vue file in Express is not working as expected在 Express 中部署 Vue 文件未按预期工作
【发布时间】:2023-03-30 13:55:01
【问题描述】:

我有一个简单的 vue 文件 (index.html)

<html>
  <body>
    <div id="example">
      <p>{{ hello }}</p>
    </div>
  </body>
</html>
<script src="js/app.js"></script>
    <script>

        new Vue({
            el: '#example',
            data: { hello: 'Hello world!' }
        })
    </script>

在浏览器中打开 index.html 文件时,打印的是Hello world。我需要在快速服务器中部署它。添加 server.js 文件如下,

const express = require('express');
const path = require('path');

const app = express();
const port = process.env.PORT || 1234;

// sendFile will go here
app.get('/', function(req, res) {
  res.sendFile(path.join(__dirname, '/public/index.html'));
});

app.listen(port);
console.log('Server started at http://localhost:' + port);

运行节点服务器时,浏览器只是呈现如下,

如果我将&lt;script src="js/app.js"&gt;&lt;/script&gt; 替换为&lt;script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"&gt;&lt;/script&gt;,它工作正常。不知道为什么使用 Vue 库作为外部文件时它不起作用。有没有办法实现这一目标?提前致谢。

【问题讨论】:

  • 成功了。更新 server.js 如下,app.use(express.static(path.join(__dirname, 'public'))); app.get('/',function(req,res) { res.redirect('index.html'); })

标签: node.js vue.js express


【解决方案1】:

只需添加这行代码

app.use(express.static(path.join(__dirname, 'public'))); 所以你的代码看起来像这样

const express = require('express');
const path = require('path');

const app = express();
const port = process.env.PORT || 1234;

app.use(express.static(path.join(__dirname, 'public')));

// sendFile will go here
app.get('/', function(req, res) {
  res.sendFile(path.join(__dirname, '/public/index.html'));
});

app.listen(port);
console.log('Server started at http://localhost:' + port);

【讨论】:

    猜你喜欢
    • 2019-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-10
    • 2022-06-11
    • 1970-01-01
    • 2017-09-08
    • 1970-01-01
    相关资源
    最近更新 更多