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.