0

I copy pasted a gfg code (https://www.geeksforgeeks.org/how-to-connect-mongodb-with-reactjs/) which connects mongodb with react.I followed the steps as mentioned but got the error "Uncaught runtime errors: ERROR JSON.parse: unexpected character at line 1 column 1 of the JSON data" All the json formats are correct and same as available in the code. My friends did the same thing but didn't encounter this error.It worked once out of the blue , I was able to send data to my mongodb compass but when I undid the changes and then copy pasted the working code it didn't work.Please Please help me rectify.

// Frontend code 
// Filename - App.js

import { useState } from 'react'

function App() {
    const [name, setName] = useState("");
    const [email, setEmail] = useState("");

    const handleOnSubmit = async (e) => {
        e.preventDefault();
        let result = await fetch(
            'http://localhost:3001/register', {
                method: "post",
                body: JSON.stringify({ name, email }),
                headers: {
                    'Content-Type': 'application/json'
                }
            }
        );
        result = await result.json();
        console.warn(result);
        if (result) {
            alert("Data saved successfully");
            setEmail("");
            setName("");
        }
    };

    return (
        <>
            <h1>This is React WebApp</h1>
            <form action="">
                <input type="text" placeholder="name" value={name} onChange={(e) => setName(e.target.value)} />
                <input type="email" placeholder="email" value={email} onChange={(e) => setEmail(e.target.value)} />
                <button type="submit" onClick={handleOnSubmit}>Submit</button>
            </form>
        </>
    );
}

export default App;

// Code for mongoose config in backend
// Filename - backend/index.js

// To connect with your mongoDB database
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/', {
    dbName: 'yourDB-name',
    useNewUrlParser: true,
    useUnifiedTopology: true
}, err => err ? console.log(err) : console.log('Connected to yourDB-name database'));

// Schema for users of app
const UserSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
    },
    email: {
        type: String,
        required: true,
        unique: true,
    },
    date: {
        type: Date,
        default: Date.now,
    },
});

const User = mongoose.model('users', UserSchema);
User.createIndexes();

// For backend and express
const express = require('express');
const app = express();
const cors = require("cors");

console.log("App listen at port 3001");

app.use(express.json());
app.use(cors());

app.get("/", (req, resp) => {
    resp.send("App is Working");
    // You can check backend is working or not by 
    // entering http://loacalhost:3001
    // If you see App is working means
    // backend working properly
});

app.post("/register", async (req, resp) => {
    try {
        const user = new User(req.body);
        let result = await user.save();
        result = result.toObject();
        if (result) {
            delete result.password;
            resp.send(req.body);
            console.log(result);
        } else {
            console.log("User already register");
        }
    } catch (e) {
        resp.send("Something Went Wrong");
    }
});

app.listen(3001);

Note:We didn't even use JSON.parse()

19
  • 3
    Show the actual error, don't paraphrase it. Just copy-paste the whole thing, and I bet it says the unexpected character was <, meaning you forgot to verify that what you got back was actual JSON instead of a 403/404/etc error web page. Commented May 10, 2024 at 20:15
  • When you debug, which specific operation produces the error? For example, if it was result = await result.json(); then your next debugging step would be to observe what actual response content the server returned, because it wouldn't be JSON. Commented May 10, 2024 at 20:16
  • @mike-pomax-kamermans The title of this post itself is the copy pasted error. Commented May 10, 2024 at 20:19
  • @David Yes the line result = await result.json(); is the error producer Commented May 10, 2024 at 20:20
  • Your title is not where details go. Your title is the summary of the problem, and the actual full error goes in your post. So to rephrase: add code that checks what you actually got from your fetch call before calling .json(), because right now your code simply assumes it's JSON, even though you have zero guarantee that it will be. Commented May 10, 2024 at 20:21

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.