invalid JSON error when clicking button in reactjs

Viewed 23

I am trying to build a simple react page where there are two buttons at the beginning. The first sends the string 'private' as response when clicked, the second sends 'public' as a response when clicked. The two strings should come from a mongodb database. It's not done yet, because whenever I click on any of the buttons, I get the same error over and over again. It's the following:

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

This project has a backend server with two GET requests and a react frontend. You can see them below. The frontend:

function PubPrivBtn() {

async function clickHandler(e) {
    if (e.target.id === 'pubBtn') {
        let response = await fetch('/api/public');
        let result = await response.json();
        console.log(result);
    }
    if (e.target.id === 'privBtn') {
        let response = await fetch('/api/private');
        let result = await response.json();
        console.log(result)
    }
}
return (
    <div>
        <button onClick={(e) => clickHandler(e)} id='pubBtn'>Public</button>
        <button onClick={(e) => clickHandler(e)} id='privBtn'>Private</button>
    </div>
)}export default PubPrivBtn;

And the backend:

import mongoose from "mongoose";
import express from "express";
import props from './porp.model.js'

const app = express();
app.use(express.json());

mongoose.connect('mongodb://localhost/auth', async (err, db) => {
    if (err) {
        console.log(err)
    }
    else{
        console.log('Connected!')
    }
    app.get('/api/public', async (req, res) => {
        let pub = await props.where("vis").equals("public")
        console.log(pub);
        res.send(pub)
    })

    app.get('/api/private', async (req, res) => {
        let priv = await props.where("vis").equals("private")
        console.log(priv);
        res.send(priv)
    })
})

app.listen(3001)

Plus the schema is const porp = new mongoose.Schema({ vis: String }).

I have tried to remake the whole project from zero (not like it was a big deal), but nothing changed, so I have to think the problem is not in my code. Or maybe I'm wrong and it's something obvious.

1 Answers

My "proxy": "http://localhost:3001", was in the wrong package.json. (the backend's) I have replaced it to the frontend and it's now working perfectly fine. Thanks @Konrad Linkowski! If I hadn't noticed it, your comment would have solved it for sure!

Related