在日志中表达静态中间件返回错误

时间:2018-10-16 05:01:15

标签: node.js express webpack-4

我在本地计算机上完成了一个项目,目前正在学习如何将其部署到生产环境。我在用于生产的文档中找到了很多东西,但现在已经停留了一段时间,我只停留在关于如何告诉服务器提供静态资产的静态内容上,这些静态资产包含我使用Web Pack执行的构建文件。出于记录,我没有使用create-react-app,而是使用了webpack-dev-server cli。

我只成功连接到服务器,并使用MySQL在服务器上运行路由,但是当开发准备投入生产时,我从未测试过如何在服务器上提供静态文件。尝试提供静态构建文件时,控制台出现错误。我无法确定错误是否是因为我的服务器上的路线服务不正确,或者index.html版本中存在问题。

这是我的代码,服务器文件很大,所以我只显示与卡住的问题有关的相关部分:

服务器文件:

const express = require("express");
const bodyParser = require("body-parser");
const path = require("path");
const cors = require("cors");
const router = express.Router();

const app = express();
const port = 5000;

app.use(cors());
// Body Parser Middleware
app.use(bodyParser.json({ limit: "50mb" }));
app.use(bodyParser.urlencoded({ extended: false }));

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  next();
});

app.get("*", function(request, response) {
  response.sendFile(path.join(__dirname + "/../public/index.html"));
});

// Serve static files on server
app.use("../", express.static(__dirname + "public/index.html"));

app.listen(port, () => {
  console.log(`Server started on port ${port}`);
});

构建Index.html文件

<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="theme-color" content="#000000">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
    crossorigin="anonymous">
  <link href='https://fonts.googleapis.com/css?family=PT+Sans:400,400italic,700' rel='stylesheet' type='text/css'>
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.1.0/css/all.css">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.1.0/css/v4-shims.css">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css" rel="stylesheet">
  <link rel="stylesheet" href="/public/assets/css/pignose.calendar.min.css">
  <link href="/public/assets/css/styles.css" rel="stylesheet" type="text/css">
  <title></title>
</head>

<body>
  <div id="root"></div>

  <script type="text/javascript" src="/public/assets/js/jquery-3.3.1.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
    crossorigin="anonymous"></script>
  <!-- Ck Editor Library -->
  <script src="/public/assets/js/plugins/ckeditor/ckeditor.js"></script>
  <!-- Pignose Calendar -->
  <script src="/public/assets/js/pignose.calendar.full.min.js"></script>
  <script type="text/javascript" src="/public/assets/js/scripts.js"></script>
</body>

</html>

Webpack生产

const webpack = require("webpack");
const path = require("path");
const CompressionPlugin = require("compression-webpack-plugin");
const nodeExternals = require("webpack-node-externals");
const HtmlWebPackPlugin = require("html-webpack-plugin");

var browserConfig = {
  entry: ["babel-polyfill", __dirname + "/src/index.js"],
  output: {
    path: path.resolve(__dirname + "/build"),
    filename: "bundle.js",
    publicPath: "/"
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
          query: {
            presets: ["react", "env", "stage-0"]
          }
        }
      },
      {
        test: /\.css$/,
        use: [
          { loader: "style-loader" },
          { loader: "css-loader" },
          { loader: "sass-loader" }
        ]
      }
    ]
  },
  plugins: [
    new CompressionPlugin({
      filename: "[path].gz[query]",
      algorithm: "gzip",
      minRatio: 0.8,
      threshold: 8192
    }),
    new webpack.DefinePlugin({
      "process.env.NODE_ENV": JSON.stringify("production")
    }),
    new HtmlWebPackPlugin({
      template: "./public/index.html"
    })
  ]
};

var serverConfig = {
  target: "node",
  externals: [nodeExternals()],
  entry: __dirname + "/server/main.js",
  output: {
    path: path.resolve(__dirname + "/build"),
    filename: "bundle.js",
    publicPath: "/"
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
          query: {
            presets: ["react", "env", "stage-0"]
          }
        }
      }
    ]
  }
};

module.exports = [browserConfig, serverConfig];

文件夹架构

Folder

当我尝试连接到构建文件的端口时出现错误日志:

enter image description here

第二次错误:

Second error log.

1 个答案:

答案 0 :(得分:1)

在明确的中间件配置中,顺序很重要,因为app.get("*", function(request, response)在顶部,每个请求都将通过该请求并发送index.html。像这样更改顺序

// Serve static files on server

app.use('/public', express.static(__dirname + "/../public"));

app.get("*", function (request, response) {
    response.sendFile(path.join(__dirname + "/../public/index.html"));
});

它应该可以工作


编辑

当您要扩展我的答案的请求时,发生的事情是由于您尚未配置公共目录,因此快递服务器将到达下一个请求处理程序app.get("*" , ...,该处理程序发送index.html作为回应。因此,当您请求此javascript文件

<script type="text/javascript" src="/public/assets/js/jquery-3.3.1.min.js"></script>

它将像我提到的那样发送index.html而不发送jquery-3.3.1.min.js,并且每个js和css文件都一样,但是您的浏览器需要一个javascript文件并尝试对其进行解析,因此文件{{ 1}}正在解析,并且由于它不是有效的JavaScript,因此会显示错误。希望有帮助