skip to Main Content

I created an context in React app which uses fetch api to connect to my server on localhost. I submit the form using handleClick function which calls the addNote function of the context. The addNote function then uses fetch to hit the api with given payload. But sending the request through the frontend shows validation errrors of minimum length of note must be 5 characters and minimum length of desription should be 5 characters. However I have checked the payload along with the error response and it shows the payload is getting sent correctly. It is not returning any error when i send the payload in postman or thunderclient.

The Context:

const TestState = (props) => {
    const host = "http://localhost:5000"
    const [notes, setNotes] = useState([])

    //ADD A NOTE
    const addNote = async (note) => {
        console.log({ theNote: note })
        const response = await fetch(`${host}/api/notes/new`, {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                "Authorization": "--JWTauthToken--"
            },
            body: JSON.stringify({ note }),
        });
        const jsonData = await response.json();
        console.log(jsonData)

    } 

The Notes Route of add new Note:

router.post("/new", [
  body("description")
    .isLength({ min: 5, max: 100 })
    .withMessage("Desc should be atleast 5 characters long"),
  body("title")
    .isLength({ min: 5 })
    .withMessage("title must be at least 5 characters long"),
  body("tag").optional(),
], fetchUser, 
async (req, res) => {
  //validationResult = Extracts the validation errors of an express request
  const result = validationResult(req);
  const result2 = result.formatWith((error) => error.msg);

  if (!result2.isEmpty()) {
    return res.status(400).json({ errors: result2.array(), body: req.body });
  }

  try {
    const { title, description, tag } = req.body;
    const note = await Notes.create({
      title,
      description,
      user: req.user.id,
      tag,
    });

    try {
      res.status(201).json(note);
    } catch (error) {
      console.error(error);
      res.status(500).json({ message: "Error in creating new Note" });
    }
  } catch (error) {
    console.error(error);
  }
});

The Addnote Component which handles the form:

const context = useContext(initContext)
    const { addNote } = context
    const [note, setnote] = useState({ title: "", description: "", tag: "" })

    const handleClick = (event) => {
        event.preventDefault();
        addNote(note)
    }
    const onChange = (event) => {
        setnote({ ...note, [event.target.name]: event.target.value })
    }

return( <>....</>)

the console error in browser:
testState.jsx:12
POST http://localhost:5000/api/notes/new 400 (Bad Request)
testState.jsx:21
{errors: Array(2), body: {…}}
body
:
note
:
description
:
"description test"
tag
:
""
title
:
"Reactjs"

errors:
Array(2)
0
:
"Desc should be atleast 5 characters long"
1
:
"title must be at least 5 characters long"
length
:
2

I tried using the Postman to check if the api is working correctly and it does. Everything works normal up till the request is sent through the frontend.

2

Answers


  1. Chosen as BEST ANSWER

    Apparantly the validator causes this error because in the fetch function i send the body directly as the whole note. I just ha to destructure the json and send and it solved the error.

    body: JSON.stringify({ note }),

    changed to

    body: JSON.stringify({ title: note.title, description: note.description, tag: note.tag}),

    although I don't exactly know the reason of this behavior but atleast the bug is gone


  2. I’m sure, I just think you forgot to enable cors option. Client-Side-Rendering cannot access server application directly.

    Here an sample example is:

    const cors = require('cors');
    
    const app = express();
    
    app.use(cors());
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search