Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

Viewed 2108

I am using MERN stack and Redux, when i try to fetch data from the MongoDb i keep getting the error 'Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data' I have tried everything and can't figure out what is causing it. Can anyone see what i am missing? I am really new to this so please go easy on me. :) I have tried using data from an external JSON placeholder URL and it all pulls through as expected but when i switch to my own data it doesn't work.

My action is:

export const fetchSubjects = () => (dispatch) => {
  console.log("fetching called");
  fetch("/api/subjects/Subject")
    .then((res) => res.json())
    .then((subjects) =>
      dispatch({
        type: FETCH_SUBJECTS,
        subjects: subjects,
      })
    );
};


My model is:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const SubjectSchema = new Schema({
  title: {
    type: String,
    required: true,
    unique: true,
  },
  summary: {
    type: String,
    required: true,
  },
  description: {
    type: String,
    required: true,
  },
  rating: {
    type: Number,
    default: 0,
  },
  author: {
    type: mongoose.ObjectId,
    default: this.users,
  },
  comments: [mongoose.ObjectId],
  date: {
    type: Date,
    default: Date.now,
  },
});

module.exports = mongoose.model("subjects", SubjectSchema);


My api is:

const express = require("express");
const subjectRouter = express.Router();
const validateSubjectInput = require("../../validation/subjectVal");
const Subject = require("../../models/Subject");

subjectRouter.post("/subject", (req, res) => {
  // Form validation
  const { errors, isValid } = validateSubjectInput(req.body);

  if (!isValid) {
    console.log("Hitting");
    return res.status(400).json(errors);
  }

  Subject.findOne({ title: req.body.title }).then((subject) => {
    if (subject) {
      return res.status(400).json({ title: "Title already exists" });
    } else {
      const newSubject = new Subject({
        title: req.body.title,
        summary: req.body.summary,
        description: req.body.description,
      });
      newSubject
        .save()
        .then((subject) => res.json(subject))
        .catch((err) => console.log(err));
    }
  });
});

module.exports = subjectRouter;
0 Answers
Related