Skip to content
Advertisement

TypeError: Failed to fetch and POST fetch status = canceled

I am passing user input data from React js to node js i.e backend, by using POST fetch api and successfully storing the data to my database. But fetch api is not returning the object successfully and showing me network status equal to canceled in google devtool. I tried every thing but I don’t know how to solve it. Thanks.

Error Screenshot Headers screenshot devtool

CustomerRegistration.jsx

const onSubmit = async (e) => {

        const { fname, lname, email, password, address } = state;

        await fetch('/customer-registration', {
            method: 'POST',
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({
                fname: fname, lname: lname, email: email, password: password, address: address
            })
        }).then((res)=>{
            console.log(`this is my res ${res}`);
            window.alert('Customer Registration successfull');
        }).catch((error)=>{
            window.alert(error);
            console.log(error);
        })
    }

Routers.js

router.post('/customer-registration',async(req,res)=>{
    
    const {fname,lname,email,password,address}=req.body;
    
    try {
        const valid=await myModel.findOne({email:email});
        if(valid){
            const flag=true;
           console.log('Email already exist');
        }else{

            const finalData=new myModel({fname,lname,email,password,address});
            const data=await finalData.save();
            if(data){
                console.log('Data saved to db');
                console.log(data);
                res.json(data);
            } 
        }
    } catch (error) {
        console.log('Data not saved');
    }

})

Advertisement

Answer

You are getting that error because you are not ensuring your nodejs returns a response.

router.post('/customer-registration',async(req,res)=>{
    
    const {fname,lname,email,password,address}=req.body;
    
    try {
        const valid=await myModel.findOne({email:email});
        if(valid){
            const flag=true;
           console.log('Email already exist');
           
        }else{

            const finalData=new myModel({fname,lname,email,password,address});
            const data=await finalData.save();
            if(data){
                console.log('Data saved to db');
                console.log(data);
                return res.json(data);
            } 

           return res.json({ok: false }) //you need to ensure you return something.
        }
    } catch (error) {
        console.log('Data not saved');
        return res.status(400).end() // you need to return something even if it's an error.
    }

})
Advertisement