简体   繁体   中英

API works fine in postman but not in frontend part of react

I am doing a project(ecommerce project) in MERN stack for practice. I am fairly new to Mern stack. Everything works fine except for "UpdateCategory" in frontend section. It works perfect in POSTMAN. In frontend part it is giving error.

I have attached the entire code related to updateCategory section including the backend part and adminapi call for reference.

Frontend side "updateCategory" code is attached just below the adminapicall below, please look at that and try to figure out whats going wrong.

Have a look at this screenshot, after clicking the update button, only the error function is working.

https://i.stack.imgur.com/ApgVu.png

----------------------------------------------adminapicall-----------------------------------------------

import { API } from "../../backend";

//category calls
export const createCategory = (userId, token, category) => {
  return fetch(`${API}/category/create/${userId}`, {
    method: "POST",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      Authorization: `Bearer ${token}`
    },
    body: JSON.stringify(category)
  })
    .then(response => {
      return response.json();
    })
    .catch(err => console.log(err));
};

//get a category
export const getCategory = categoryId => {
  return fetch(`${API}/category/${categoryId}`, {
    method: "GET"
  })
    .then(response => {
      return response.json();
    })
    .catch(err => console.log(err));
};

//get all categories
export const getCategories = () => {
  return fetch(`${API}/categories`, {
    method: "GET"
  })
    .then(response => {
      return response.json();
    })
    .catch(err => console.log(err));
};

//delete a category
export const deleteCategory = (categoryId, userId, token) => {
  return fetch(`${API}/category/${categoryId}/${userId}`, {
    method: "DELETE",
    headers: {
      Accept: "application/json",
      Authorization: `Bearer ${token}`
    }
  })
    .then(response => {
      return response.json();
    })
    .catch(err => console.log(err));
};

//update a category

export const updateCategory = (categoryId, userId, token, category) => {
  return fetch(`${API}/category/${categoryId}/${userId}`, {
    method: "PUT",
    headers: {
      Accept: "application/json",
      Authorization: `Bearer ${token}`
    },
    body: category
  })
    .then(response => {
      return response.json();
    })
    .catch(err => console.log(err));
};

//products calls

//create a product
export const createaProduct = (userId, token, product) => {
  return fetch(`${API}/product/create/${userId}`, {
    method: "POST",
    headers: {
      Accept: "application/json",
      Authorization: `Bearer ${token}`
    },
    body: product
  })
    .then(response => {
      return response.json();
    })
    .catch(err => console.log(err));
};

//get all products
export const getProducts = () => {
  return fetch(`${API}/products`, {
    method: "GET"
  })
    .then(response => {
      return response.json();
    })
    .catch(err => console.log(err));
};

//delete a product

export const deleteProduct = (productId, userId, token) => {
  return fetch(`${API}/product/${productId}/${userId}`, {
    method: "DELETE",
    headers: {
      Accept: "application/json",
      Authorization: `Bearer ${token}`
    }
  })
    .then(response => {
      return response.json();
    })
    .catch(err => console.log(err));
};

//get a product

export const getProduct = productId => {
  return fetch(`${API}/product/${productId}`, {
    method: "GET"
  })
    .then(response => {
      return response.json();
    })
    .catch(err => console.log(err));
};

//update a product

export const updateProduct = (productId, userId, token, product) => {
  return fetch(`${API}/product/${productId}/${userId}`, {
    method: "PUT",
    headers: {
      Accept: "application/json",
      Authorization: `Bearer ${token}`
    },
    body: product
  })
    .then(response => {
      return response.json();
    })
    .catch(err => console.log(err));
};

--------------------------------------------UpdateCategory-----------------------------------------------

import React, { useState,useEffect } from "react";
import Base from "../core/Base";
import { isAutheticated } from "../auth/helper";
import { Link } from "react-router-dom";
import { getCategory, updateCategory } from "./helper/adminapicall";




const UpdateCategory = ({match}) => {
    const [name, setName] = useState("");
    const [error, setError] = useState(false);
    const [success, setSuccess] = useState(false);
    const { user, token } = isAutheticated();

    const preload = categoryId => {
        getCategory(categoryId).then(data =>{
            if(data.error) {
                console.log(data.error);
            }else{
                setName(data.name)
            }
        });
    };

    useEffect(() => {
        preload(match.params.categoryId);
      }, []);


    const goBack = () => (
      <div className="mt-5">
        <Link className="btn btn-sm btn-success mb-3" to="/admin/dashboard">
          Admin Home
        </Link>
      </div>
    );


    const handleChange = event => {
      setError("");
      setName(event.target.value);
    };


      const onSubmit = event => {
        event.preventDefault();
        setError("");
        setSuccess(false);

          //backend request fired 
          updateCategory(match.params.categoryId, user._id, token, { name }).then(data => {
            if (data.error) {
              setError(true);
            } else {
              setError("");
              setSuccess(true);
              setName("");
            }
          });
        };



            const successMessage = () => {
                if (success) {
                  return <h4 className="text-success">Category created successfully</h4>;
                }
              };

        const warningMessage = () =>{
            if(error){
                return <h4 className="text-danger">Failed to update</h4>
            }
        };



        const myCategoryForm = () =>(
            <form> 
                <div className="form-group">
                    <p className="lead">Enter the category</p>
                    <input 
                    type="text"
                    className="form-control my-3"
                    onChange={handleChange}
                    value={name}
                    autoFocus
                    required
                    placeholder="For Ex.Summer"
                    />
                    <button onClick={onSubmit} className="btn btn-outline-info">
                        Update Category
                        </button>
                </div>
            </form>
        );


    return (
        <Base 
        title="Update a category here!!"
        description="Update Categories here"
        className="container bg-info p-4"> 

        <div className="row bg-white rounded">
            <div className="col-md-8 offset-md-2">
                {successMessage()}
                {warningMessage()}
                {myCategoryForm ()}
                {goBack ()}
            </div>
        </div>
        </Base>
    );
};

export default UpdateCategory;






import { API } from "../../backend";

//category calls
export const createCategory = (userId, token, category) => {
  return fetch(`${API}/category/create/${userId}`, {
    method: "POST",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      Authorization: `Bearer ${token}`
    },
    body: JSON.stringify(category)
  })
    .then(response => {
      return response.json();
    })
    .catch(err => console.log(err));
};

//get a category
export const getCategory = categoryId => {
  return fetch(`${API}/category/${categoryId}`, {
    method: "GET"
  })
    .then(response => {
      return response.json();
    })
    .catch(err => console.log(err));
};

//get all categories
export const getCategories = () => {
  return fetch(`${API}/categories`, {
    method: "GET"
  })
    .then(response => {
      return response.json();
    })
    .catch(err => console.log(err));
};

//delete a category
export const deleteCategory = (categoryId, userId, token) => {
  return fetch(`${API}/category/${categoryId}/${userId}`, {
    method: "DELETE",
    headers: {
      Accept: "application/json",
      Authorization: `Bearer ${token}`
    }
  })
    .then(response => {
      return response.json();
    })
    .catch(err => console.log(err));
};

//update a category

export const updateCategory = (categoryId, userId, token, category) => {
  return fetch(`${API}/category/${categoryId}/${userId}`, {
    method: "PUT",
    headers: {
      Accept: "application/json",
      Authorization: `Bearer ${token}`
    },
    body: category
  })
    .then(response => {
      return response.json();
    })
    .catch(err => console.log(err));
};

//products calls

//create a product
export const createaProduct = (userId, token, product) => {
  return fetch(`${API}/product/create/${userId}`, {
    method: "POST",
    headers: {
      Accept: "application/json",
      Authorization: `Bearer ${token}`
    },
    body: product
  })
    .then(response => {
      return response.json();
    })
    .catch(err => console.log(err));
};

//get all products
export const getProducts = () => {
  return fetch(`${API}/products`, {
    method: "GET"
  })
    .then(response => {
      return response.json();
    })
    .catch(err => console.log(err));
};

//delete a product

export const deleteProduct = (productId, userId, token) => {
  return fetch(`${API}/product/${productId}/${userId}`, {
    method: "DELETE",
    headers: {
      Accept: "application/json",
      Authorization: `Bearer ${token}`
    }
  })
    .then(response => {
      return response.json();
    })
    .catch(err => console.log(err));
};

//get a product

export const getProduct = productId => {
  return fetch(`${API}/product/${productId}`, {
    method: "GET"
  })
    .then(response => {
      return response.json();
    })
    .catch(err => console.log(err));
};

//update a product

export const updateProduct = (productId, userId, token, product) => {
  return fetch(`${API}/product/${productId}/${userId}`, {
    method: "PUT",
    headers: {
      Accept: "application/json",
      Authorization: `Bearer ${token}`
    },
    body: product
  })
    .then(response => {
      return response.json();
    })
    .catch(err => console.log(err));
};

----------------------------------------------ManageCategory---------------------------------------------

import React , {useState,useEffect} from 'react'
import Base from '../core/Base'
import { Link } from 'react-router-dom';
import { isAutheticated } from '../auth/helper';
import { getCategories, deleteCategory} from './helper/adminapicall';




const ManageCategories= () => {

  const [categories, setCategories] = useState([]);

  const { user, token } = isAutheticated();

  const preload = () => {
    getCategories().then(data => {
      if (data.error) {
        console.log(data.error);
      } else {
        setCategories(data);
      }
    });
  };

  useEffect(() => {
    preload();
  }, []);

  const deleteThisCategory = categoryId => {
    deleteCategory(categoryId, user._id, token).then(data => {
      if (data.error) {
        console.log(data.error);
      } else {
        preload();
      }
    });
  };




  return (
    <Base title="Welcome admin" description="Manage products here">
      <h2 className="mb-4">All products:</h2>
      <Link className="btn btn-info" to={`/admin/dashboard`}>
        <span className="">Admin Home</span>
      </Link>
      <div className="row">
        <div className="col-12">
          <h2 className="text-center text-white my-3">Total 4 categories</h2>

          {categories.map((category, index) => {
            return (
              <div key={index} className="row text-center mb-2 ">
                <div className="col-4">
                  <h3 className="text-white text-left">{category.name}</h3>
                </div>
                <div className="col-4">
                <Link
                    className="btn btn-success"
                    to={`/admin/category/update/${category._id}`}       
                  >
                    <span className="">Update</span>
                  </Link>
                </div>
                <div className="col-4">
                  <button
                    onClick={() => {
                      deleteThisCategory(category._id);
                    }}
                    className="btn btn-danger"
                  >
                    Delete
                  </button>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </Base>
  );
};
export default ManageCategories;

-------------------------------------------UpdateCategory------------------------------------------------

import React, { useState,useEffect } from "react";
import Base from "../core/Base";
import { isAutheticated } from "../auth/helper";
import { Link } from "react-router-dom";
import { getCategory, updateCategory } from "./helper/adminapicall";




const UpdateCategory = ({match}) => {
    const [name, setName] = useState("");
    const [error, setError] = useState(false);
    const [success, setSuccess] = useState(false);
    const { user, token } = isAutheticated();

    const preload = categoryId => {
        getCategory(categoryId).then(data =>{
            if(data.error) {
                console.log(data.error);
            }else{
                setName(data.name)
            }
        });
    };

    useEffect(() => {
        preload(match.params.categoryId);
      }, []);


    const goBack = () => (
      <div className="mt-5">
        <Link className="btn btn-sm btn-success mb-3" to="/admin/dashboard">
          Admin Home
        </Link>
      </div>
    );


    const handleChange = event => {
      setError("");
      setName(event.target.value);
    };


      const onSubmit = event => {
        event.preventDefault();
        setError("");
        setSuccess(false);

          //backend request fired 
          updateCategory(match.params.categoryId, user._id, token, { name }).then(data => {
            if (data.error) {
              setError(true);
            } else {
              setError("");
              setSuccess(true);
              setName("");
            }
          });
        };



            const successMessage = () => {
                if (success) {
                  return <h4 className="text-success">Category created successfully</h4>;
                }
              };

        const warningMessage = () =>{
            if(error){
                return <h4 className="text-danger">Failed to update</h4>
            }
        };



        const myCategoryForm = () =>(
            <form> 
                <div className="form-group">
                    <p className="lead">Enter the category</p>
                    <input 
                    type="text"
                    className="form-control my-3"
                    onChange={handleChange}
                    value={name}
                    autoFocus
                    required
                    placeholder="For Ex.Summer"
                    />
                    <button onClick={onSubmit} className="btn btn-outline-info">
                        Update Category
                        </button>
                </div>
            </form>
        );


    return (
        <Base 
        title="Update a category here!!"
        description="Update Categories here"
        className="container bg-info p-4"> 

        <div className="row bg-white rounded">
            <div className="col-md-8 offset-md-2">
                {successMessage()}
                {warningMessage()}
                {myCategoryForm ()}
                {goBack ()}
            </div>
        </div>
        </Base>
    );
};

export default UpdateCategory;

---------------------------------------------Category(controller)----------------------------------------

const Category = require("../models/category");

exports.getCategoryById = (req, res, next, id) => {
  Category.findById(id).exec((err, cate) => {
    if (err) {
      return res.status(400).json({
        error: "Category not found in DB"
      });
    }
    req.category = cate;
    next();
  });
};

exports.createCategory = (req, res) => {
  const category = new Category(req.body);
  category.save((err, category) => {
    if (err) {
      return res.status(400).json({
        error: "NOT able to save category in DB"
      });
    }
    res.json({ category });
  });
};

exports.getCategory = (req, res) => {
  return res.json(req.category);
};

exports.getAllCategory = (req, res) => {
  Category.find().exec((err, categories) => {
    if (err) {
      return res.status(400).json({
        error: "NO categories found"
      });
    }
    res.json(categories);
  });
};

exports.updateCategory = (req, res) => {
  const category = req.category;
  category.name = req.body.name;

  category.save((err, updatedCategory) => {
    if (err) {
      return res.status(400).json({
        error: "Failed to update category"
      });
    }
    res.json(updatedCategory);
  });
};

exports.removeCategory = (req, res) => {
  const category = req.category;

  category.remove((err, category) => {
    if (err) {
      return res.status(400).json({
        error: "Failed to delete this category"
      });
    }
    res.json({
      message: "Successfull deleted"
    });
  });
};

try this

UpdateCategory.jsx

....
....
const onSubmit = (event, val) => {
  event.preventDefault();
  setError("");
  setSuccess(false);

  //backend request fired
  updateCategory(match.params.categoryId, user._id, token, { name:val }).then(
    (data) => {
      if (data.error) {
        setError(true);
      } else {
        setError("");
        setSuccess(true);
        setName("");
      }
    }
  );
};
....
....
  <button onClick={(e)=> onSubmit(e, name)} className="btn btn-outline-info">
    Update Category
  </button>
....
....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM