【问题标题】:How run node.js server with React?如何使用 React 运行 node.js 服务器?
【发布时间】:2020-08-26 11:14:11
【问题描述】:

我正在尝试使用 React 实现我的 node.js 服务器。我已经用 react 配置了 webpack,但我不知道如何在我的服务器上启动它。是否可以不使用 express.js? 现在它只是渲染 index.html 而没有其他存在于 react 中的页面。 谢谢!

Webpack.config

const HtmlWebPackPlugin = require("html-webpack-plugin");
const path = require('path');

module.exports = {
  entry: "./src/index.js",
  output: {
    path: path.join(__dirname, 'dist'),
    filename: "main.js"
  },
  plugins: [
    new HtmlWebPackPlugin({
      template: "./src/index.html", 
      filename: "./index.html"
    })
  ],
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
            loader: "babel-loader",
            options: {
              presets: ['@babel/preset-env','@babel/preset-react'],
          }
        }
      },
      {
        test: /\.scss$/,
        use: ['style-loader','css-loader','sass-loader']
      }
    ]
  }
};

server.js

const http = require("http");
const path = require("path");
const fs = require("fs");
const indexFile = path.join(__dirname, "../src", "index.html");

const server = http.createServer((req, res) => {
  if (req.url === "/") {
    fs.readFile(indexFile, "utf-8", (err, content) => {
      if (err) {
        throw err;
      }
      res.end(content);
    });
  }
});

server.listen(3000, () => {
  console.log("server is running");
});

package.json

  "scripts": {
    "dev": " webpack --mode development && node server/server.js",
    "build": "webpack --mode production"
  },

【问题讨论】:

    标签: javascript node.js reactjs webpack localhost


    【解决方案1】:

    您需要确保将 express 设置为提供静态文件,例如:

    app.use(express.static(path.join(__dirname, "dist/build")));
    

    并使用 sendFile 代替 readFile:

    app.get('*', (req, res, next) => {
      res.sendFile(path.join(__dirname, "/dist/build", "index.html"));
    });
    

    【讨论】:

    • 如果可能的话,我尝试在没有快递的情况下这样做。我也尝试运行path.join(__dirname, "../dist", "index.html") ,但结果相同。它不起作用
    • 哦,我明白了,我只是假设您使用的是快递!仅使用 Node 本身肯定会更棘手 - 看看这篇文章,它会详细介绍 Node:medium.com/@amitgupta15/…
    猜你喜欢
    • 2014-12-31
    • 2021-07-29
    • 2015-06-16
    • 1970-01-01
    • 2016-03-25
    • 1970-01-01
    • 1970-01-01
    • 2013-04-19
    • 1970-01-01
    相关资源
    最近更新 更多