skip to Main Content

So I’m having issues making a connection to localhost:3001/insert but I don’t see what the issue may be.

registerdb.js

const express = require("express");
const mysql = require("mysql2");
const app = express();
const db = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "DanaRoot5!",
  database: "OurProjectSchema",
});
const bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.post("/insert", (req, res) => {
  const body = req.body;
  const sql = `INSERT INTO customer (customer_ID, SSN, address, full_name, date_of_registration) VALUES (?, ?, ?, ?, ?)`;
  const values = [
    body.customer_ID,
    body?.SSN,
    body?.address,
    body?.full_name,
    body?.date_of_registration,
  ];

  db.query(sql, values, (error, results) => {
    if (error) {
      console.log(body);
      console.error("Error executing query: " + error.stack);
      res.status(500).send("Error adding customer");
      return;
    }

    console.log("Query results:", results);
    res.status(200).send("Customer added successfully");
  });
});

app.listen(3001, () => {
  console.log("Server started on port 3001");
});

Register.jsx

import React, { useState } from "react";
const { v4: uuidv4 } = require("uuid");

export const Register = (props) => {
  const [SSN, setSSN] = useState("");
  const [name, setName] = useState("");
  const [address, setAddress] = useState("");
  const handleSubmit = (e) => {
    e.preventDefault();
    const date = new Date().toISOString().slice(0, 19).replace("T", " ");
    const customer_id = uuidv4();

    fetch("http://localhost:3001/insert", {
      mode: "no-cors",
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        customer_ID: customer_id,
        SSN: SSN,
        address: address,
        full_name: name,
        date_of_registration: date,
      }),
    })
      .then((response) => {
        console.log(response);
        if (!response.ok) {
          throw new Error("Network response was not ok");
        }
        return response.json();
      })
      .then((data) => {
        console.log(data);
        // display success message to user
      })
      .catch((error) => {
        console.error(error);
        // display error message to user
      });
  };

  return (
    <div className="auth-form-container">
      <h2>Register</h2>
      <form className="register-form" onSubmit={handleSubmit}>
        <label htmlFor="name">Full Name</label>
        <input
          value={name}
          name="name"
          onChange={(e) => setName(e.target.value)}
          id="name"
          placeholder="Full Name"
        />
        <label htmlFor="SSN">SSN/SIN</label>
        <input
          value={SSN}
          onChange={(e) => setSSN(e.target.value)}
          type="text"
          placeholder="SSN/SIN"
          id="SSN"
          name="SSN"
        />
        <label htmlFor="Address">Address</label>
        <input
          value={address}
          onChange={(e) => setAddress(e.target.value)}
          type="text"
          placeholder="Address"
          id="Address"
          name="Address"
        />
        <button type="submit">Register</button>
      </form>
      <button className="link-btn" onClick={() => props.onFormSwitch("login")}>
        Already have an account? Login here.
      </button>
    </div>
  );
};

So I know that the connection between my local database and the node/express works since I have created an app.get("/select") route and that worked ie localhost:3001/select works.

However, app.post("/insert) does not. I am getting the following message: Cannot GET /insert and in the console I’m getting:

GET http://localhost:3001/insert 404 (Not Found)

I tried testing the localhost:3001/insert with curl but that did not work either.

I also tried playing around with the URL in the fetch statement. But that did not help either.

Both files are on different branches. registerdb.js is on a server github branch and Register.jsx is on a client github branch.

May I please receive some guidance/tips?

2

Answers


  1. Your endpoint is POST but the error mentions

    Cannot GET /insert

    Most likely, the way you do the post, from the browser side, is not a POST but a GET.

    If you are using fetch you need to pass the option method:'POST'

    fetch(url, {
      method: 'POST'
    });
    
    Login or Signup to reply.
  2. This is hard to debug without having an idea of how you are submitting that request, but it seems that the wrong HTTP verb is being used (GET instead of POST). There could be many reasons for that depending on how you are submitting your request.

    Assuming that you’re using a form to submit data to the /insert route, do you have your method="POST" set on the form element?

    Otherwise, are you able to share how you are making the request?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search