Vasita
Vasita

Reputation: 11

Uncaught runtime errors: ERROR JSON.parse: unexpected character at line 1 column 1 of the JSON data

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()

Upvotes: 0

Views: 74

Answers (0)

Related Questions