Skip to content

Request sends Twice returns HTTP 500 Error #297

Open
@ApetweBc

Description

@ApetweBc

I send a POST request to a API server and the request sent 2 times. The initial request succeed because the records are inserted in the database then I get HTTP 500 response from the server. I have attached the error response and added the payload request. In the forms I have deleted the some of the inputs to make it readable here.

Debug Console
Preview Tab

resource: [{code: "23000",…}]
0: {code: "23000",…}
code: "23000"
message: "SQLSTATE[23000]: [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Violation of PRIMARY KEY constraint 'PK_Customers'. Cannot insert duplicate key in object 'dbo.Customers'. The duplicate key value is (James-1520). (SQL: insert into [dbo].[Customers] ([CustomerID], [SalesPerson], [LabName], [CreatedBy], [Deleted]) values (James-1520, 0, 1, James, James, Dr, , Kwaku Clinic, 115 Ave, Toronto, AB, M5B 2P7, , Canada, 6833733, [email protected], More, 1, Prospects Form, 0))"
trace: [,…]
message: "Batch Error: Not all requested records could be created."
status_code: 500

Server Logs
[2022-06-30T16:34:27.114490+00:00] local.INFO: [RESPONSE] {"Status Code":500,"Content-Type":null}
[2022-06-30T16:34:27.115436+00:00] local.INFO: [RESPONSE] {"Status Code":200,"Content-Type":null}

Example code

Base URL

import { create } from "apisauce";


const apiClient = axios.create({
  baseURL: "http://****",
  headers: {
    "X-API-KEY":
      "45566****",
    // "X-pplication-Name": "testMore",
    // "Access-Control-Allow-Origin": "*",
    // "Access-Control-Allow-Methods": "GET, POST, PUT, PATCH, DELETE, OPTIONS",
    // "Access-Control-Allow-Headers": "Content-Type, Authorization",
    // "Access-Control-Allow-Credentials": true,
    "Content-Type": "application/json",
    Accept: "application/json",
    "access-control-allow-credentials": true,
    "access-control-allow-methods": "*",
    "access-control-allow-origin": "*",
    "access-control-allow-headers": "*",
    "cache-control": "no-cache",
    "cors-enabled": false,
  },
  // params: {},
});

export default apiClient;

Endpoint

import apiClient from "./apiBaseUrl";
const addCustomers = "_table/Customers/";
const addProspects = (_prospect) => {
  const resource = JSON.stringify([
    {
      labID: _prospect.labID,
      LabName: _prospect.labName,
      // deleted the  following lines because they are not needed
      Deleted: _prospect.deleted,
    },
  ]);
  console.log(resource);
  apiClient.post(
    addCustomers,
    resource
  
  );
  return apiClient.post(addCustomers, resource);
};

export default addProspects;

Form

/ Validation schema for the form
const validateSchema = Yup.object().shape({
  firstName: Yup.string().required().label("First Name"),
});

// Customer Id and Padding for the it
const strl = 30;
const initialNumber = 10;
const randomNumber = Math.floor(Math.random() * 100);
const custID = initialNumber + randomNumber + strl.toString().padStart(2, 3);

const Prospects = () => {
  // Function to handle the submit of the form
  const handleSubmit = async (values) => {
    const result = await apiEndPoints({
      ...values,
    });

    if (result.status >= 400 && result.status < 500) {
      console.log("400 Errors " + result.originalError);

    } else if (result.status >= 500) {

      console.log(result.config);
    } else if (result.problem) {

      console.log(result.config);
    } else {
      console.log("200 Success " + result.status);
    }
  };

  // Initial values for the form
  const initialValues = {
    active: false,
    prospect: true,
    customerID: custID,
    firstName: "",
 
  };

  return (
    <>

      <Layout>
        <div>
          <Formik
            initialValues={{
              ...initialValues,
            }}
            onSubmit={handleSubmit}
            validationSchema={validateSchema}
            enableReinitialize={true}
          >
            {({
              values,
              handleChange,
              handleBlur,
              handleSubmit,
            }) => (
              <form onSubmit={handleSubmit}>
                <Toast />
             
                  <div>
                    <label htmlFor="" className="relative block">
                      <span className="my-3"> Dr FirstName </span>
                      <input
                        type="text"
                        name="firstName"
                        id=""
                        onChange={handleChange}
                        onBlur={handleBlur}
                        value={values.firstName}
                      />
                    </label>
                  </div>
         
                <button
                  type="submit"
                  onClick={handleSubmit}
                >
                  Submit
                </button>
              </form>
            )}
          </Formik>
        </div>
      </Layout>
    </>
  );
};

export default Prospects;

Expected behavior

Expect only 1 request to be sent
Response of 200

Environment

  • ApiSauce Version [2.1.5]
  • Adapter [XHR/HTTP]
  • Browser [Chrome, Edge]
  • Browser Version [ Edge 103.0.1264.37 (Official build) (64-bit), Chrome 03.0.5060.66 (Official Build) (64-bit)]
  • Node.js Version
  • OS: [Windows 10]
  • React 18.0.1

Screenshots
image

image

image

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions