mongodb 在MERN中插入表单数据时出错

mnemlml8  于 2022-12-03  发布在  Go
关注(0)|答案(2)|浏览(236)

我是stackOverflow和Reactjs的新手,我已经尝试过许多其他类似的问题,但它们没有帮助
我正在尝试使用节点和express从react到mongodb数据库中惰性化表单数据。我正在使用FETCH API发送我的表单数据。但是在chrome控制台中有两个错误。

第一个错误

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

  • 对于这个错误,我用了 *

"proxy": "http://localhost:4000"在我的package.json(reactjs)中,但仍然有错误 *

第二个错误

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

  • 我不知道这是什么 *
    请指导我如何处理所有这些错误
    Reister.js( reactjs js)
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 class=" container position-relative z-index-9">
                <div class="row g-4 g-sm-5 justify-content-between">
                    <div class=" hero-rah mb-5 col-12 col-lg-6 d-md-flex align-items-center justify-content-center  bg-opacity-10 vh-lg-100">
                        <div class="p-3 p-lg-5">
                            <div class="text-center">
                                <h2 class="fw-bold">Welcome to our largest community</h2>
                                <p class="mb-0 h6 fw-light">Let's learn something new today!</p>
                            </div>
                            <img src={zerotwo} class="mt-5" alt="" />
                        </div>
                    </div>
                    <div class="col-lg-6 position-relative">
                        <div class=" jk mt-5 bg-primary bg-opacity-10 rounded-3 p-4 p-sm-5">
                            <h2 class="mb-3">Register Here</h2>
                            <form method='POST' class="row g-4 g-sm-3 mt-2 mb-0">
                                <div class="col-12">
                                    <label class="form-label">Name *</label>

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

                                    />
                                    {/* {errors.username && touched.username ? (<span class="badge badge-danger">{errors.username}</span>) : null} */}

                                </div>

                                <div class="col-12">
                                    <label class="form-label">Email *</label>

                                    <input type="email"
                                        class="form-control"
                                        name='email'
                                        value={user.email}
                                        onChange={handleInput}

                                    />
                                    {/* {errors.email && touched.email ? (<span class="badge badge-danger">{errors.email}</span>) : null} */}

                                </div>

                                <div class="col-12">
                                    <label class="form-label">Mobile number *</label>

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

                                    />
                                    {/* {errors.mobile && touched.mobile ? (<span class="badge badge-danger">{errors.mobile}</span>) : null} */}

                                </div>

                                <div class="col-12">
                                    <label class="form-label">Password *</label>

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

                                    />
                                    {/* {errors.password && touched.password ? (<span class="badge badge-danger">{errors.password}</span>) : null} */}

                                </div>
                                <div class="col-12">
                                    <label class="form-label">Confirm Password *</label>

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

                                    />
                                    {/* {errors.cpassword && touched.cpassword ? (<span class="badge badge-danger">{errors.cpassword}</span>) : null} */}

                                </div>

                                <div class="col-12 d-grid">
                                    <button onClick={PostData} type="submit" class="btn btn-lg btn-primary mb-0">Register</button>
                                </div>
                            </form>

授权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

应用程序.js(后端)

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}`);
})

注册模式

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

我曾尝试在reactjs中使用fect api插入表单数据,但我希望数据能插入到数据库中。

iq3niunx

iq3niunx1#

如果您使用的是节点服务器,请安装此npm install body-parser并将以下行添加到服务器端代码常量中

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

如果您使用的是应用程序const app = express();,则可以简单地使用app.use(bodyParser.json());
在您代码中,
在提取时也使用完整的端口名。

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

bf1o4zei2#

它应该是const router = express.Router()而不是router = express()而且它应该是module.exports而不是module. Exports

相关问题