mysql - 找不到模块 : Can't resolve 'fs' in '.../node_modules/destroy' using Next. js mysql Express React

标签 mysql reactjs express next.js

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

结构

  • 组件
  • 页数
    • index.js
  • 路线
    • routes.js
  • 服务器.js
  • package.json

因错误而失败:

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

但是 server.js 中的 /routes/routes 可以工作。

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

最佳答案

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

但是 除了将请求发送到自身之外,我仍然需要其他方法。

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);
    });

关于mysql - 找不到模块 : Can't resolve 'fs' in '.../node_modules/destroy' using Next. js mysql Express React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60021821/

相关文章:

reactjs - 如何在开发过程中将本地 React 库与本地 React 项目链接?

javascript - 如何使<input>值灵活

node.js - NodeJS/Express : Get Username and Password from Request

php - 在 yii2 中插入数据库?

php - 检查表1中的用户名并返回表2中的数据

Node.js在Webpack中的作用是什么?

node.js - header 未使用 node.js/Express 设置重定向

php - 使用 PHP 将 latin1_swedish_ci 转换为 utf8

mysql - 如何查看MySQL全文索引的索引内容?

node.js - Express.js - ./bin/www 背后的目的