【问题标题】:Vue js deploying in production seems harder then it is在生产中部署 Vue js 似乎更难
【发布时间】:2019-01-28 15:52:53
【问题描述】:

我使用 Vue-cli 3 创建了简单的 Vue JS 应用程序。我有一个带有 Nginx + php 的 digitalocean 液滴。 我的目标是在同一个 droplet 上托管 Vue App。 我已经试过了:

我得到的是 sUncaught SyntaxError: Unexpected token <:

有趣的是,当我使用npm run build 将生产资源放入dist 目录并使用php -S localhost:8080 时,它就像一个魅力一样托管。但是与简单的节点 js 服务器相同的事情会导致上面屏幕截图中的结果。

我已经连续挣扎了 2 天。请帮帮我。

【问题讨论】:

  • 听起来可能是您的 nginx 配置文件中的语法错误。在此处发布。

标签: nginx vue.js deployment vue-cli-3


【解决方案1】:

我在同样的问题上苦苦挣扎。问题是当浏览器请求 javascript 和 css 文件时,会发送索引文件的内容。

按照tutorial的第3步解决了这个问题。

由于 Vue 只是一个前端库,托管它的最简单方法和 做诸如提供资产之类的事情是为了创建一个简单的 Express 友好 Heroku 可以用来启动迷你网络服务器的脚本。快速阅读 如果您还没有,请在 Express 上。之后,添加快递:

npm install express --save

现在将 server.js 文件添加到项目的根目录:

// server.js

var express = require('express');
var path = require('path');
var serveStatic = require('serve-static');

app = express();
app.use(serveStatic(__dirname + "/dist"));

var port = process.env.PORT || 5000;
app.listen(port);

console.log('server started '+ port);

之后,由于最初的想法是为 index.html 提供服务,所以我借用了这个 idea 并将以下内容添加到我的代码中(请注意,如果请求是 html,我使用了 sendFile):

app.use((req, res, next) => {
    res.status(404)

    if (req.accepts("html")) {
        res.sendFile(path.join(__dirname + "/dist/index.html"))
        return
    }

    if (req.accepts("json")) {
        res.send({error: "Not found"})
        return
    }

    res.type("txt").send("Not found")
})

【讨论】:

    【解决方案2】:

    有点晚了,但我已经用这个来sendFile index.html 404 响应。

    app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(404).sendFile(path.resolve(__dirname, "dist", "index.html"));
    })
    

    说明: err 将在请求错误时定义。 res.status 将状态设置为 404 代码,应用程序将 sendFile 解析的 index.html。 (请注意,为了安全起见,我同时使用了 __dirname 和 path.resolve 来构建绝对路径。

    【讨论】:

      猜你喜欢
      • 2019-11-22
      • 1970-01-01
      • 1970-01-01
      • 2019-11-06
      • 2015-02-06
      • 2021-05-24
      • 2020-10-29
      • 2017-08-11
      • 2021-04-01
      相关资源
      最近更新 更多