Home > Software engineering >  Error while Inserting the form data in MERN
Error while Inserting the form data in MERN

Time:12-03

I am new to stackOverflow and Reactjs, i had tried many other problem like them but they didn't help

I aam trying to inert the form data from react to mongodb database using node and express. and i am using FETCH API to send my form data. but there are two errors in chrome console.

First error

POST http://localhost:3000/register 404 (Not Found)

*For this error i had used *

"proxy": "http://localhost:4000" in my pakage.json(reactjs) but still there is error*

second error

VM18761:1 Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON

I dont know what is this

please guide me how to tackle all of these error

Reister.js(reactjs)

import React, { useState } from 'react'
import zerotwo from "../images/07.svg"
// import { Formik, useFormik } from 'formik'
// import { Signupschema } from '../Form-Validation/Schema'




const Signup = () => {

    const [user, setUser] = useState({
        username: "",
        email: "",
        mobile: "",
        password: "",
        cpassword: ""
    })

    let name, value
    const handleInput = (e) => {
        name = e.target.name
        value = e.target.value
        setUser({ ...user, [name]: value })
    }


    const PostData = async (e) => {
        
        e.preventDefault()
        const { username, email, mobile, password, cpassword } = user
        
        const res = await fetch("/register", {
            method: "POST",
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },

            body: JSON.stringify({
                username, email, mobile, password, cpassword
            })
        })

        const data = await res.json()
        

        if (data === 422 || !data) {
            alert("not registered")
        } else {
            alert("Sucesssfuly")
        }
    }

    return (
        <div>
            <div >
                <div >
                    <div >
                        <div >
                            <div >
                                <h2 >Welcome to our largest community</h2>
                                <p >Let's learn something new today!</p>
                            </div>
                            <img src={zerotwo}  alt="" />
                        </div>
                    </div>
                    <div >
                        <div >
                            <h2 >Register Here</h2>
                            <form method='POST' >
                                <div >
                                    <label >Name *</label>

                                    <input type="text"
                                        
                                        aria-label="First name"
                                        name='username'
                                        value={user.username}
                                        onChange={handleInput}

                                    />
                                    {/* {errors.username && touched.username ? (<span >{errors.username}</span>) : null} */}


                                </div>

                                <div >
                                    <label >Email *</label>

                                    <input type="email"
                                        
                                        name='email'
                                        value={user.email}
                                        onChange={handleInput}

                                    />
                                    {/* {errors.email && touched.email ? (<span >{errors.email}</span>) : null} */}

                                </div>

                                <div >
                                    <label >Mobile number *</label>

                                    <input type="text"
                                        
                                        aria-label="Mobile number"
                                        name='mobile'
                                        value={user.mobile}
                                        onChange={handleInput}

                                    />
                                    {/* {errors.mobile && touched.mobile ? (<span >{errors.mobile}</span>) : null} */}

                                </div>

                                <div >
                                    <label >Password *</label>

                                    <input type="password"
                                        
                                        aria-label="password"
                                        name='password'
                                        value={user.password}
                                        onChange={handleInput}

                                    />
                                    {/* {errors.password && touched.password ? (<span >{errors.password}</span>) : null} */}

                                </div>
                                <div >
                                    <label >Confirm Password *</label>

                                    <input type="password"
                                        
                                        aria-label="password"
                                        name='cpassword'
                                        value={user.cpassword}
                                        onChange={handleInput}

                                    />
                                    {/* {errors.cpassword && touched.cpassword ? (<span >{errors.cpassword}</span>) : null} */}

                                </div>

                                <div >
                                    <button onClick={PostData} type="submit" >Register</button>
                                </div>
                            </form>

Auth.js

const express = require("express")
const router = express()
const bcrypt = require("bcryptjs")
const jwt = require("jsonwebtoken")

require("../conn")
const User = require("../models/SignupSchema")

router.get("/", (req, res) => {
    res.send("hello i am home router js")
})

router.post("/register", (req, res) => {
    const { username, email, mobile, password, cpassword } = req.body
    if (!username || !email || !mobile || !password || !cpassword) {
        return res.status(422).json({ error: "please fill all the data" })
    }
    User.findOne({ email: email }).then((userExit) => {
        if (userExit) {
            return res.status(422).json({ error: "User is already registered" })
        }

        const user = new User({ username, email, mobile, password, cpassword })

        user.save().then(() => {
            res.status(200).json({ message: "user is registered" })
        }).catch(() => {
            res.status(500).json({ error: "Error while registering the user" })
        })
    }).catch((err) => {
        console.log(err);
    })
})



router.post("/login", async (req, res) => {
    let token
    try {
        const { email, password } = req.body
        if (!email || !password) {
            return res.status(400).json({ message: "fill the credentials" })
        }

        const UserLogin = await User.findOne({ email: email })

        if (UserLogin) {

            const passmatch = await bcrypt.compare(password, UserLogin.password)

            token = await UserLogin.generateAuthToken()
            console.log(token);
            res.cookie("jwt",token,{
                expires : new Date(Date.now() 25892000000),
                httpOnly : true
            })

            if (!passmatch) {
                res.status(400).json({ error: "Invalid credentials" })
            }
            else {
                res.status(200).json({ message: "sign in successfully" })
            }
        } else {
            res.status(400).json({ error: "Invalid credentials" })
        }

    } catch (err) {
        console.log(err);
    }
})

module. Exports = router


App.js(backend)

const dotenv = require("dotenv")
const express = require("express")
const app = express()

dotenv.config({path:"./config.env"})
require("./conn")
app.use(express.json())
const PORT = process.env.PORT

app.use(require("./router/Auth"))

const middleware = (req,res,next)=>{
    console.log("i am using middleware");
    next();
}


app.get("/",(req,res)=>{
    res.send("hello world from the server")
})

app.get("/about",middleware,(req,res)=>{
    res.send("this is about page rahul")
})
app.listen(PORT,()=>{
    console.log(`server is listening ${PORT}`);
})

signup schema

const mongoose = require("mongoose")
const bcrypt = require("bcryptjs")
const jwt = require("jsonwebtoken")

const SignupSchema = new mongoose.Schema({
    username: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    mobile: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    cpassword: {
        type: String,
        required: true
    },
    tokens:[
        {
            token:{
                type:String,
                required:true
            }
        }
    ]
})

SignupSchema.pre("save", async function (next) {
    console.log("hi i am pre");
    if (this.isModified("password")) {
        console.log("hi i am pre password");
        this.password = await bcrypt.hash(this.password, 12)
        this.cpassword = await bcrypt.hash(this.cpassword, 12)
        next()

    }
})

SignupSchema.methods.generateAuthToken = async function () {
    try {
        let token = jwt.sign({ _id:this._id},process.env.SECRET_KEY)
        this.tokens = this.tokens.concat({token:token})
        await this.save()
        return token
    } catch (err) {
        console.log(err);
    }
}

const Signup = mongoose.model("SIGNUP", SignupSchema)
module. Exports = Signup

I had tried to insert my form data using fect api in reactjs abd i expecting to data to be inserted in my database

CodePudding user response:

If you are using node server, install this npm install body-parser and add these lines in your server-side code const

`bodyParser = require("body-parser"); 
 router.use(bodyParser.json());`

if you are using app const app = express(); then you can simply use app.use(bodyParser.json());
in your code,

also use the full port name while fetch.

fetch("http://localhost:3000/register");

CodePudding user response:

it should be const router = express.Router() not router = express() and it's module.exports not module. Exports.

  • Related