How to start your node server.js with React

I am trying to connect my node server.js with React app. I've already set up webpack, but I don't know how to run it from my server. Is it possible without using express.js? Now I just have a renderit index.html no other pages that exist in React. Thanks!

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"
  },

Index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, maximum-scale=1"
    />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Kittens</title>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

Index.js

import React from "react";
import ReactDOM from "react-dom";
import App from "./App/App";

const app = <App />;

ReactDOM.render(app, document.getElementById("root"));
Author: Volodumr, 2020-08-26

1 answers

You don't send anything other than the index.html itself. Try something similar:

const path = require('path');
const http = require('http');
const fs = require('fs');

const server = http.createServer((req, res) => {
  const filePath = path.basename(req.url) || path.join(__dirname, '../src',  'index.html');

  fs.readFile(filePath, (err, content) => {
    if (err) return;
    res.end(content);
  })
});

server.listen(3000);
 0
Author: Yoskutik, 2020-08-26 14:10:39