繁体   English   中英

如何使用 React 运行 node.js 服务器?

[英]How run node.js server with React?

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

配置文件

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']
      }
    ]
  }
};

服务器.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");
});

包.json

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

您需要确保将 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"));
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM