8

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: 'john@gmail.com',
        password: 'cookies',
        entries: 0,
        joined: new Date()
    },
    {
        id: '124',
        name: 'Tom',
        email: 'Tom@gmail.com',
        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)
  }
Tom Larry
  • 101
  • 1
  • 1
  • 5
  • 1
    You are fetching wrong port. Your server listening on 3002 port so on fetch change it url to "http://localhost:3002". And on your get request use "res.json()" instead "res.send", this will return the response with correct header. For details you can [check this](https://stackoverflow.com/questions/19041837/difference-between-res-send-and-res-json-in-express-js). – Nasir Uddin Sep 03 '22 at 09:06

3 Answers3

6

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)
  }
Aaron
  • 151
  • 6
1

For those using Next.js, make sure that the api related files are in api folder.

Sunil Kumar Das
  • 372
  • 1
  • 2
  • 12
0

In my case, it was an issue with the React package.json file.

I added the "proxy": "http://localhost:8080", to the package.json file. so the problem was fixed.

React is running on port 3000, and express is running on port 8080

Nasser Ali Karimi
  • 4,462
  • 6
  • 34
  • 77