0

I would like to insert data from pages/index.js into mysql database. A mysql connection in routes/routes.js, i have built ins function to call what i want

Structure

  • components
  • pages
    • index.js
  • routes
    • routes.js
  • server.js
  • package.json

Fail with error:

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

But /routes/routes in server.js work.

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

I am new at Next.js and React. There is a better way to insert data from pages/index.js into mysql database? Please let me know.

"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 Ver 14.14 Distrib 5.7.28, Node v12.14.1

1
  • Please add text instead of images
    – nbk
    Feb 1, 2020 at 23:05

2 Answers 2

0

At last, i have to post request to my server via the same server on frontend(index.js) to insert data into mysql database. I'm not sure. because of SSR(Next.js), i cannot send data back to backend.

But I still need other method except post request into itself.

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

As long as we don't run next build and don't start app with NODE_ENV=production, this issue won't happen. We use NODE_ENV=dev to circumvent this issue for the moment. I mean we use npm run dev to deploy now. This can only be considered a temporary solution.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.