微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何使用React运行Node.js服务器?

我正在尝试用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"
  },

解决方法

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。