'i am getting error like validation error and also 404 error and enter all field..please check it...i also attached an image

enter image description here

Im giving all details in form filed still i get the error: enter all fields....

and also im gettind error like /api/user 404 not found dont know why

if i try this in postman i get the output as expexted but not in frontend part

My userController.js file

const asyncHandler = require("express-async-handler");
// const res = require('express/lib/response');
const generateToken = require("../config/generateToken");
const User = require("../Models/userModel");

const registerUser = asyncHandler(async (req, res) => {
  const { name, email, password, pic } = req.body;

  if (!email || !password || !name) {
    res.status(404);
    throw new Error("please enter all fields");
  }

  const userExists = await User.findOne({ email });

  if (userExists) {
    res.status(404);
    throw new Error("user already exists");
  }

  const user = await User.create({
    name,
    email,
    password,
    pic,
  });

  if (user) {
    res.status(201).json({
      _id: user._id,
      name: user.name,
      email: user.email,
      pic: user.pic,
      token: generateToken(user._id),
    });
  } else {
    throw new Error("user not found");
  }
});

const authuser = asyncHandler(async (req, res) => {
  const { email, password } = req.body;

  const user = await User.findOne({ email });

  if (user && (await user.matchPassword(password))) {
    res.json({
      _id: user._id,
      name: user.name,
      email: user.email,
      isAdmin: user.isAdmin,
      pic: user.pic,
      token: generateToken(user._id),
    });
  } else {
    res.status(401);
    throw new Error("Invalid Email or Password");
  }
});

module.exports = { registerUser, authuser };

My userRoutes.js

const express = require('express');
const{ registerUser  , authuser}= require('../controller/userController');


const router = express.Router();

router.route('/').post(registerUser) 
router.route('/login').post(authuser);

module.exports = router;

My Signup.js

import { Button, FormControl, FormLabel, Input, InputGroup, InputRightElement, toast, useToast, VStack } from '@chakra-ui/react'
import axios from 'axios'
// import res from 'express/lib/response'
// import res from 'express/lib/response'
import React, { useState } from 'react'
import { useHistory } from 'react-router-dom'

const Signup = () => {

    const [show, setShow] = useState(false)
    const [showcon, setShowcon] = useState(false)
    const [name, setName] = useState()
    const [email, setemail] = useState()
    const [confirmpassword, setconfirmpassword] = useState()
    const [password, setpassword] = useState()
    const [pic, setPic] = useState()
    const [loading, setLoading] = useState(false)   
    const toast = useToast();
    const history = useHistory()

    const postDetails = (pics)=> {
        setLoading(true)
        if(pics===undefined){
            toast({
                title:'Please select an image',
                status:'warning',
                duration:5000,
                isClosable:true,
                position:'bottom'
            })
            return;
        } 
        console.log(pics)
        if(pics.type==="image/jpeg" || pics.type === "image/png")
        {
            const data = new FormData();
            data.append("file" ,pics);
            data.append("upload_preset" , "chat-app");
            data.append("cloud_name" , "dxvwfoybv")
            fetch("https://api.cloudinary.com/v1_1/dxvwfoybv/image/upload" , {
                method:'post', body:data,
            }).then((res) => res.json())
            .then((data) => {
                setPic(data.url.toString());
                console.log(data.url.toString());
                setLoading(false);
            }).catch((err) => {
                console.log(err);
                setLoading(false);
            })
        }else{
            toast({
                title: "Please Select an Image!",
                status: "warning",
                duration: 5000,
                isClosable: true,
                position: "bottom",
              });
              setLoading(false);
              return;
        }
    }

    const handleClick =() => {
        setShow(!show);
    }

    const submithandler =async() => {
        //  setLoading(true);
         if(!name || !email || !password || !confirmpassword){
             toast({
                 title:"please fill all details",
                 status: 'warning',
                 duration:'5000',
                 isClosable:true,
                 position:'bottom'
             })
             return;
         }

         try {
             const config = {
                 headers: {
                     "content-type" : "application/json",

                 }
             }
             const data  = await axios.post("/api/user" , {name , email , password , pic}. config);

             toast({
                 title:"Registration successfull",
                 status: "success",
                 duration: 5000,
                 position: "bottom",
                 isClosable: true
             })
             localStorage.setItem('userInfo', JSON.stringify(data));

             setLoading(false);
             history.push('/chats')

         } catch (error) {
             toast({
                title:"Error occured",
                status: "error",
                description:error.response.data.message,
                duration: 5000,
                position: "bottom",
                isClosable: true
             })
         }
    }

    
    // const handleClickcon =() => {
    //     setShowcon(!showcon)
    // }

    console.log()

  return (
      <>
    <VStack spacing='5px'>
        
        <FormControl name='firstname'>
            <FormLabel>Name</FormLabel>
               <Input
                    
                    placeholder='Enter Your Name'
                    value={name}
                    onChange={(e)=>setName(e.target.value)}
               /> 
        </FormControl>

        <FormControl>
        <FormLabel>Email</FormLabel>
               <Input
                    type='email'
                    placeholder='Enter Your Email address'
                    value={email}
                    onChange={(e)=>setemail(e.target.value)}
               /> 
        </FormControl>

        <FormControl>
        <FormLabel>Password</FormLabel>
            <InputGroup>
               <Input

                    type={show?  "" : "password"}
                    placeholder='Enter Your Password'
                    value={password}
                    onChange={(e)=>setpassword(e.target.value)}
               /> 

                <InputRightElement width='4.5rem'>
                    <Button h='1.75rem' size='sm' onClick={handleClick}>
                        {
                            show? "Hide" : "Show"
                        }    
                    </Button>

                </InputRightElement>

            </InputGroup>
        </FormControl>

        <FormControl>
        <FormLabel>Confirm Password</FormLabel>
            <InputGroup>
               <Input

                    type={show?  "" : "password"}
                    placeholder='Enter Your Password'
                    value={confirmpassword}
                    onChange={(e)=>setconfirmpassword(e.target.value)}
               /> 

                <InputRightElement width='4.5rem'>
                    
                            
                    

                </InputRightElement>

            </InputGroup>
        </FormControl>

        <FormControl>
            <FormLabel>Upload your Picture</FormLabel>
            <Input type='file' p='1.5' accept='image/*' onChange={(e) => postDetails(e.target.files[0])}>                
            </Input>

        </FormControl>  


        <Button
            colorScheme='blue'
            width='100%'
            style={{marginTop: '20px'}}
            onClick={submithandler}
            isLoading={loading}
        >Sign up</Button>      
    
    </VStack>

    </>
  )
}

export default Signup


Solution 1:[1]

I think the problem come from the request body the front send. In the front code, make a console log of the body request before it sent and show us.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 louisBrochet