简体   繁体   English

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

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

I am trying implement my node.js server with React.我正在尝试使用 React 实现我的 node.js 服务器。 I already configure webpack with react but I dont know how I can start it wit my server.Is it possible without using express.js?我已经用 react 配置了 webpack,但我不知道如何用我的服务器启动它。是否可以不使用 express.js? Now it is just render index.html without other pages which exist in react.现在它只是渲染 index.html,没有其他存在于 react 中的页面。 Thank you!谢谢!

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服务器.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包.json

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

You need to make sure that express is set to serve static files, eg:您需要确保将 express 设置为提供静态文件,例如:

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

And use sendFile instead of readFile:并使用 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