crud – How do I pass data to the backend using Reactjs?

The backend is working properly with the Postman. but it not working correctly with my front end. This error occurs when I try to add a product. I used the Axios to send HTTP requests from the frontend to the backend. Please can you help me solve this error

Access to XMLHttpRequest at 'http://localhost:8070/products/' from origin 'http://localhost:1234' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

This is my AddProduct.js file.

import axios from "axios";
import React, { useState } from "react";
    
export default function AddProduct() {
  const [name, setName] = useState();
  const [description, setDescription] = useState();
  const [qty, setQty] = useState(0);
  const [price, setPrice] = useState(0);

  const handleSubmit = async (e) => {
    e.preventDefault();
    const data = {
      name,
      description,
      qty,
      price,
    };
    console.log("data", data);

    const insert = await axios
      .post("http://localhost:8070/products/", data)
      .then(() => {
        alert("Product Added successfully");
        e.target.reset();
      })
      .catch((err) => {
        alert("Failed: " + err.message);
      });
  };

  return (
    <div className="p-5 m-5">
      <form onSubmit={handleSubmit}>
        <div className="mb-3">
          <label className="form-label">Name</label>
          <input
            type="text"
            className="form-control"
            onChange={(e) => setName(e.target.value)}
          />
        </div>
        <div className="mb-3">
          <label className="form-label">Description</label>
          <textarea
            className="form-control"
            onChange={(e) => setDescription(e.target.value)}
          />
        </div>
        <div className="mb-3">
          <label className="form-label">Quantity</label>
          <input
            type="number"
            className="form-control"
            onChange={(e) => setQty(e.target.value)}
          />
        </div>
        <div className="mb-3">
          <label className="form-label">Price</label>
          <input
            type="number"
            className="form-control"
            onChange={(e) => setPrice(e.target.value)}
          />
        </div>
        <button type="submit" className="btn btn-primary">
          Submit
        </button>
      </form>
    </div>
  );
}

This is my AllProduct.js file.

import React, { useEffect, useState } from "react";
import axios from "axios";
import { useNavigate } from "react-router-dom";

export default function AllProduct() {
  const [product, setProduct] = useState();
  const navigate = useNavigate();
  var sum;

  useEffect(() => {
    axios
      .get(`http://localhost:8070/products/`)
      .then((res) => {
        setProduct(res.data);
      })
      .catch((err) => {
        alert("Failed: " + err.message);
      });
  }, []);
  console.log(product);

  const handleDelete = async (id) => {
    let ans = window.confirm("Do you want to delete this product ?");

    if (ans) {
      await axios
        .delete(`http://localhost:8070/products/${id}`)
        .then(() => {
          alert("Delete Successfully");
          window.location.reload(false);
        })
        .catch((err) => {
          alert("Failed: " + err.message);
        });
    }
  };

  const handleEdit = (product) => {
    let { _id, name, description, qty, price } = product;
    console.log("product", product);

    localStorage.setItem("pID", _id);
    localStorage.setItem("pName", name);
    localStorage.setItem("pDescription", description);
    localStorage.setItem("pQty", qty);
    localStorage.setItem("pPrice", price);
    navigate("/edit");
  };

  return (
    <div className="p-5 m-5">
      <table className="table">
        <thead>
          <tr>
            <th scope="col"></th>
            <th scope="col">Name</th>
            <th scope="col">Description</th>
            <th scope="col">Quantity</th>
            <th scope="col">Price</th>
            <th scope="col"></th>
            <th scope="col"></th>
          </tr>
        </thead>
        <tbody>
          {product?.map((product, index) => (
            <tr key={index}>
              <th scope="row">{index + 1}</th>
              <td>{product.name}</td>
              <td>{product.description}</td>
              <td>{product.qty}</td>
              <td>{product.price}</td>

              <td>
                <button
                  className="btn btn-danger"
                  onClick={() => handleDelete(product._id)}
                >
                  Delete
                </button>
              </td>
              <td>
                <button
                  className="btn btn-warning"
                  onClick={() => handleEdit(product)}
                >
                  Edit
                </button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
      {
        (sum = product
          ?.map((product) => Number(product.price.replace("$", "")))
          .reduce((prev, curr) => prev + curr, 0))
      }
    </div>
  );
}

This is my editProduct.js

import React, { useEffect, useState } from "react";
import axios from "axios";
import { useNavigate } from "react-router-dom";

export default function EditProduct() {
  const navigate = useNavigate();
  const [id, setId] = useState();
  const [name, setName] = useState();
  const [description, setDescription] = useState();
  const [qty, setQty] = useState();
  const [price, setPrice] = useState();

  useEffect(() => {
    setId(localStorage.getItem("pID"));
    setName(localStorage.getItem("pName"));
    setDescription(localStorage.getItem("pDescription"));
    setQty(localStorage.getItem("pQty"));
    setPrice(localStorage.getItem("pPrice"));
  }, []);

  const handleUpdate = (e) => {
    e.preventDefault();
    const updateData = {
      name,
      description,
      qty,
      price,
    };
    console.log("id 27 ", id);
    axios
      .put(`http://localhost:8070/products/${id}`, updateData)
      .then(() => {
        alert("Product Update");
        navigate("/all");
      })
      .catch((err) => {
        alert(err);
      });
  };

  return (
    <div className="p-5 m-5">
      <form onSubmit={handleUpdate}>
        <div className="mb-3">
          <label className="form-label">Name</label>
          <input
            type="text"
            className="form-control"
            value={name}
            onChange={(e) => setName(e.target.value)}
          />
        </div>
        <div className="mb-3">
          <label className="form-label">Description</label>
          <textarea
            className="form-control"
            value={description}
            onChange={(e) => setDescription(e.target.value)}
          />
        </div>
        <div className="mb-3">
          <label className="form-label">Quantity</label>
          <input
            type="number"
            className="form-control"
            value={qty}
            onChange={(e) => setQty(e.target.value)}
          />
        </div>
        <div className="mb-3">
          <label className="form-label">Price</label>
          <input
            type="number"
            className="form-control"
            value={price}
            onChange={(e) => setPrice(e.target.value)}
          />
        </div>
        <button type="submit" className="btn btn-warning" href="/all">
          update
        </button>
      </form>
    </div>
  );
}

Leave a Comment