找不到模块:无法使用 Next.js mysql Express React 解析 '.../node_modules/destroy' 中的 'fs'

Module not found: Can't resolve 'fs' in '.../node_modules/destroy' using Next.js mysql Express React

我想将数据从 pages/index.js 插入到 mysql 数据库中。 routes/routes.js 中的 mysql 连接,我内置了 ins 函数来调用我想要的

结构

失败并出现错误:

Module not found: Can't resolve 'fs' in '.../node_modules/destroy'

pages/index.js

import React, { Component } from "react";
import { Typography, Button, Grid } from "@material-ui/core";
import QRCode from "qrcode.react";
import dynamic from "next/dynamic";
import { PublicKey, SecretKey, HOSPCODE } from "../stellar";


const { ins } = require("../routes/routes"); //This is the problem!

const StellarSdk = require("stellar-sdk");
const QrReader = dynamic(() => import("react-qr-reader"), {
  ssr: false
});

export default class QR extends Component {
  state = {
    result: "",
    camera: true,
    msg: "",
    QR: {}
  };
  _clear = () => {
    this.setState({ result: "", camera: true, msg: "", QR: {} });
  };
  handleScan = data => {
    if (data) {
      const dataJson = JSON.parse(data);
      if (dataJson.Type == "Patient") {
        const KP = StellarSdk.Keypair.fromSecret(SecretKey);
        this.setState({
          result: dataJson,
          QR: JSON.stringify({
            Type: "Hospital",
            HospitalName: "xxx Hospital",
            EndPoint: "xxx/patientID_",
            SPK: PublicKey,
            Signature: KP.sign(
              Buffer.from(dataJson.ID + dataJson.SPK)
            ).toString("base64")
          }),
          camera: false,
          msg: ""
        });
        ins(dataJson.ID, HOSPCODE, dataJson.SPK, dataJson.SecretKey);
      } else {
        this.setState({
          msg: "Wrong QRCode."
        });
      }
    }
  };

但是/routes/routesserver.js工作。

const express = require("express");
const next = require("next");
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();
const bodyParser = require("body-parser");
const { router, ins } = require("./routes/routes");

app
  .prepare()
  .then(() => {
    const server = express();
    server.use(bodyParser.json());
    server.use(bodyParser.urlencoded({ extended: false }));
    server.use("/api", router);
    server.get("*", (req, res) => {
      return handle(req, res);
    });

    server.listen(3001, err => {
      if (err) throw err;
      console.log("> Ready on http://localhost:3001");
    });
  })
  .catch(ex => {
    console.error(ex.stack);
    process.exit(1);
  });

routes/routes.js

const express = require("express");
const mysql = require("mysql");
const router = express.Router();
const dotenv = require("dotenv").config();

const connection = mysql.createConnection({
  host: process.env.DATABASE_HOST,
  database: process.env.DATABASE_NAME,
  user: process.env.DATABASE_USERNAME,
  password: process.env.DATABASE_PASSWORD,
  port: 3306
});

console.log("Connecting...");
connection.connect(function(err) {
  if (err) return new Error("An error occured during SQL connection " + err);
  console.log("Connected!");
});
console.log(connection.config);

/* GET home page. */
router.get("/", function(req, res, next) {
...
...
...
ins = (cid, HOSPCODE, spk, secretKey) => (cid, HOSPCODE, spk, secretKey) => {
  var sql = "INSERT INTO STELLARKEY (CID, HOSPCODE, SPK, SecretKey) VALUES ?";
  var values = [[cid, HOSPCODE, spk, secretkey]];
  connection.query(sql, [values], function(err, result) {
    if (err) throw err;
  });
};
module.exports = { router, ins };

我是 Next.js 和 React 的新手。有更好的方法将数据从 pages/index.js 插入到 mysql 数据库吗?请告诉我。

"dependencies": {
    "@material-ui/core": "^4.9.0",
    "@material-ui/icons": "^4.5.1",
    "body-parser": "^1.19.0",
    "dotenv": "^8.2.0",
    "express": "^4.17.1",
    "fs": "^0.0.1-security",
    "mysql": "^2.18.1",
    "next": "^9.2.1",
    "qrcode.react": "^1.0.0",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "react-qr-reader": "^2.2.1",
    "stellar-sdk": "^3.3.0",
    "typeface-roboto": "^0.0.75"
  }

Ubuntu 18.04 x64, mysql 版本 14.14 分发版 5.7.28, 节点 v12.14.1

最后,我必须 post 通过前端相同的服务器 (index.js) 请求我的服务器将数据插入 mysql 数据库。 我不确定。由于 SSR(Next.js),我无法将数据发送回后端。

但是 除了 post 请求自身之外,我还需要其他方法。

routes/routes.js

router.post("/secret/", cors(corsOptions), function(req, res, next) {
  var sql = "INSERT INTO STELLARKEY (CID, HOSPCODE, SPK, SecretKey) VALUES ?";
  var values = [
    [req.body.cid, req.body.HOSPCODE, req.body.spk, req.body.secretkey]
  ];
  connection.query(sql, [values], function(err, result) {
    if (err) console.log(err);
  });
});
module.exports = router;

pages/index.js

fetch("http://localhost:3001/api/secret", {
          method: "POST",
          headers: {
            Accept: "application/json",
            "Content-Type": "application/json"
          },
          body: JSON.stringify({
            cid: dataJson.ID,
            HOSPCODE: HOSPCODE,
            spk: dataJson.SPK,
            secretkey: dataJson.SecretKey
          })
        });

server.js

const router = require("./routes/routes");

app
  .prepare()
  .then(() => {
    const server = express();
    server.use(bodyParser.json());
    server.use(bodyParser.urlencoded({ extended: false }));
    server.use("/api", router);
    server.get("*", (req, res) => {
      return handle(req, res);
    });

只要我们不 运行 next build 并且不使用 NODE_ENV=production,不会出现这个问题。 我们暂时使用 NODE_ENV=dev 来规避这个问题。我的意思是我们现在使用 npm 运行 dev 进行部署。这只能算是临时解决方案。

  "scripts": {
    "dev": "NODE_ENV=dev node server.js",
    "start": "node server.js",
    "deploy": "next build && NODE_ENV=production node server.js"
  }