-1

I am working on a React/MySQL registration page. The insert query runs, but is not inserting into the database table. I am not sure why.

In the backend folder, I have my server.js file:

const express = require("express");
const mysql = require("mysql");
const cors = require("cors");

const app = express();
app.use(cors());
app.use(express.json());

const db = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "",
  database: "my_db",
});

app.post("/signup", (req, res) => {
  const sql = "INSERT INTO login (`name`, `email`, `password`) VALUES (?)";
  const values = [req.body.name, req.body.email, req.body.password];
  db.query(sql, [values], (err, data) => {
    if (err) return res.json(err);
    return res.json(data);
  });
});

app.listen(8081, () => {
  console.log("Listening...");
});    

In my frontend folder, I have App.js that looks like this:

import React from "react";
import SignUp from "./SignUp";

function App() {
  return <SignUp></SignUp>;
}

export default App;

And then my SignUp.js file:

import React, { useState } from "react";
import axios from "axios";

function SignUp() {
  const [values, setValues] = useState({
    name: "",
    email: "",
    password: "",
  });
  const handleChange = (event) => {
    setValues({ ...values, [event.target.name]: [event.target.value] });
  };
  const handleSubmit = (event) => {
    event.preventDefault();
    axios
      .post("http://localhost:8081/signup", values)
      .then((res) => console.log("Registered Successfully"))
      .catch((err) => console.log(err));
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
          type="text"
          placeholder="Enter Name"
          name="name"
          className="form-control rounded-0"
          onChange={handleChange}
        />
      // 2 more inputs for email and password
    </form>
  );
}

export default SignUp;

NPM start is used to run the backend and frontend.

I am using MAMP server which is running phpMyAdmin on localhost:8888

The form is up and running, and when I enter name, email, and password, the console reads "Registered Successfully" but upon refreshing the database, no records were inserted.

I understand that the query can run successfully without inserting anything, but in this case, I'm not sure why the query is not inserting properly.

What did I do wrong and how can I fix it?

Edit

I made the below edit to server.js as suggested by Phil and MatBailie in the comments below:

app.post("/signup", (req, res) => {
  const sql =
    "INSERT INTO login (`name`, `email`, `password`) VALUES (?, ?, ?)";
  const values = [req.body.name, req.body.email, 
req.body.password];
  db.query(sql, values, (err, data) => {
    // if (err) return res.json(err);
    // return res.json(data);
    if (err) {
      console.error("Error in signup", err);
      return res.sendStatus(500);
    }
  });
});

I am getting the below Axios error in the console:

POST http://localhost:8081/signup 500 (Internal Server Error)

In the network tab, I am seeing this:

enter image description here

Edit 2

The response section of the Axios error reads the following:

enter image description here

14
  • "the console reads 'Registered Successfully'"... that's because you return any errors as 200 Success. Change your backend code to use if (err) return res.status(500).send(err). I would also advise logging any errors in your server-side code so you can be made aware of them
    – Phil
    Commented Jul 1 at 1:03
  • You can also use your browser's dev-tools Network panel to inspect the actual response body
    – Phil
    Commented Jul 1 at 1:05
  • @Phil - I returned a 500 error, the exact same one I posted in the answer provided by Odri below. Commented Jul 1 at 1:10
  • 1
    Use (?,?,?) rather than (?) and then use values rather than [values]
    – MatBailie
    Commented Jul 1 at 1:25
  • 1
    Probably a duplicate of node.js mysql error: ECONNREFUSED
    – Phil
    Commented Jul 1 at 1:55

2 Answers 2

1

try this

const sql = "INSERT INTO login (`name`, `email`, `password`) VALUES (?, ?, ?)";

or

const sql = "INSERT INTO login SET ?";
db.query(sql, request.body, (err, data) => {
   if (err) return res.json(err);
   return res.json(data);
});
3
  • Testing........ Commented Jul 1 at 1:00
  • No luck on either. The first example ran the query successfully, but nothing was saved in the database. The second example yielded an an axios error. Commented Jul 1 at 1:06
  • 1
    While the SET ? method is neat, I wouldn't blindly pass it request.body, at least not without validation
    – Phil
    Commented Jul 1 at 1:31
0

Turns out the MAMP server was my issue. After switching to XAMPP, I was able to capture the form data into the database.

1
  • This isn't really an answer that will help other readers. The two products you mention do largely the same thing, and both will run the code you have supplied (if they are configured correctly). The real error is likely to be a server side problem (e.g. an unhandled exception) or possibly pointing at the wrong local port (see Phil's suggested duplicate on the ECONNREFUSED error).
    – halfer
    Commented Jul 8 at 21:23

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