Home > Net >  React, Node Express, Mysql registration form stuck
React, Node Express, Mysql registration form stuck

Time:04-13

I'm learning how to connect my front end to a database using middleware and trying to clone a waiver/registration form for a project my buddy gave me.

I can manually input data from the code editor to Mysql database but once I try to link it to the front end I get nothing, I'm completely stumped, can't really find any updated documentation on Node express syntax and mysql.

Here is my server and database code:

const express = require("express");
const app = express();
const mysql = require("mysql");
const bodyParser = require("body-parser");
const cors = require("cors");

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

app.use(express.json());

app.use(bodyParser.urlencoded({ extended: true }));

app.get("/api/get", (req, res) => {
  const sqlGet = "SELECT * FROM customer_registration";
  db.query(sqlGet, (error, result) => {
    res.send(result);
  });
});

app.post("/api/post", (req, res) => {
  const { firstName, lastName, email, phone, nickName } = req.body;
  const sqlInsert =
    "INSERT INTO customer_registration (firstName, lastName, email, phone, nickName) VALUES (?,?,?,?,?)";
  db.query(
    sqlInsert,
    [firstName, lastName, email, phone, nickName],
    (error, result) => {
      if (error) {
        console.log(error);
      }
    }
  );
});

heres my registration form.

  import React, { useState } from "react";
import "./NewCustomer.css";
import { Link, useNavigate } from "react-router-dom";
import { toast } from "react-toastify";
import axios from "axios";

const initialState = {
  firstName: "",
  lastName: "",
  email: "",
  phone: "",
  nickName: "",
};

export default function NewCustomer() {
  const [state, setState] = useState(initialState);

  const { firstName, lastName, email, phone, nickName } = state;

  const navigate = useNavigate();

  const handleSubmit = (e) => {
    e.preventDefalut();
    if (!firstName || !lastName || !email || !phone || !nickName) {
      toast.error("Please Provide value into each input field");
    } else {
      axios
        .post("http://localhost:3001/api/post", {
          firstName,
          lastName,
          email,
          phone,
          nickName,
        })
        .then(() => {
          setState({
            firstName: "",
            lastName: "",
            email: "",
            phone: "",
            nickName: "",
          });
        })
        .catch((err) => toast.error(err.response.data));
      setTimeout(() => navigate.push("/"), 500);
    }
  };

  // const handleInputChange = (e) => {
  //   const { name, value } = e.target;
  //   setState({ ...state, [name]: value });
  // };

  return (
    <div className="container">
      <div className="new-customer-reg">
        <Link to="/">
          <button className="center-button-startover">Start Over</button>
        </Link>
        <div className="form-in">
          <form onSubmit={handleSubmit} className="new-customer-form">
            <label for="firstName">First Name*</label>
            <input
              type="text"
              name="first_name"
              required
              // value={firstName}
              // onChange={handleInputChange}
            />
            <br />
            <label for="lastName">Last Name*</label>
            <input
              type="text"
              name="last_name"
              required
              // value={lastName}
              // onChange={handleInputChange}
            />
            <br />
            <label for="email">Email*</label>
            <input
              type="email"
              className="email"
              required
              // value={email}
              // onChange={handleInputChange}
            />
            <br />
            <label for="phone">Phone*</label>
            <input
              type="tel"
              className="phone"
              required
              // value={phone}
              // onChange={handleInputChange}
            />
            <br />
            <label for="nickName">Nickname</label>
            <input
              type=" text"
              className="nickname"
              // value={nickName}
              // onChange={handleInputChange}
            />
            <div className="input-with-optional">
              <span className="nick-helper">
                (optional) This will be displayed instead of your first name.
              </span>
              <br />
            </div>
            <button onSubmit={handleSubmit} type="submit" className="regi">
              Register
            </button>
          </form>
        </div>
      </div>
    </div>
  );
}enter code here

CodePudding user response:

You forgot to send a response from your POST route handler. For example:

res.send('Customer created')

Additionally, in your frontend you have a typo (preventDefalut) which will make your code crash.

  • Related