Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
My backend in node.js
and express.js
import express from 'express';
import bcrypt from 'bcrypt-nodejs';
import cors from 'cors';
const app = express();
app.use(express.urlencoded({extended: false}));
app.use(express.json());
app.use(cors());
const database = { users: [
{
id: '123',
name: 'John',
email: '[email protected]',
password: 'cookies',
entries: 0,
joined: new Date()
},
{
id: '124',
name: 'Tom',
email: '[email protected]',
password: 'apple',
entries: 0,
joined: new Date()
}
}
app.get('/', (req, res) =>{
res.send(database.users)
})
app.listen(3002, () => {
console.log('app is running on port 3002');
})
My frontend is in React.js
It is a big project so I will only show the part that is causing the error which the response.json()
part. When you get rid of json()
everything is fine but in order for me to recieve data from backend i need to do .json()
which gives that error. Let me know if additional info is needed
componentDidMount(){
fetch('http://localhost:3000')
.then(response => response.json())
.then(console.log)
}
CodePudding user response:
Looks like your backend is exposed on port 3002 but you're fetching on port 3000 which I assume is your local development UI. The DOCTYPE
response is indicative of you receiving HTML rather than a JSON response. Change the port of your fetch to point towards your backend and it should work:
componentDidMount(){
fetch('http://localhost:3002')
.then(response => response.json())
.then(console.log)
}
CodePudding user response:
I am also facing that type of error. In previous times, it works perfectly and loads my desired data without any interruption. But in recent times, It makes the below error.
Error Image: error description here