Home > Software engineering >  "Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0" ERROR --
"Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0" ERROR --

Time:05-14

I'm trying to fetch an array from my user database from my react app. The response I'm getting is an HTML file, but I'm not sure why it's not working as I have the same code working perfectly for a non-array element. Here is the code:

Client:

  async function populateFavorite() {
    const req = await fetch("http://localhost:3001/api/favorite", {
      headers: {
        "x-access-token": localStorage.getItem("token"),
      },
    });

    const data = await req.json();
    if (data.status === "ok") {
      console.log(data.watchlist)
    } else {
      alert(data.error);
    }
  }
 

At the moment, it looks like it's not getting past here:

const data = await req.json();

Server:


app.get('/api/favorite', async (req, res) => {
    const token = req.headers['x-access-token']

    try {
        const decoded = jwt.verify(token, '<key>')
        const email = decoded.email
        const user = await User.findOne({ email: email })

        return res.json({ status: 'ok', watchlist: user.watchlist })
    } catch (error) {
        console.log(error)
        res.json({ status: 'error', error: 'invalid token' })
    }
})

This is what the data looks like in the database:

{"_id":{"$oid":"627306d86089cb6e720e0e8a"},
"firstName":"Ailany",
"email":"[email protected]",
"coins_owned":[],
"watchlist":["Bitcoin","Serum"],
"dateCreated":{"$date":{"$numberLong":"1651705560381"}},
"__v":{"$numberInt":"0"}

The goal is to, upon rendering the site, have the client receive the array of items in the user's watchlist to then have them render separately in a list.

Any help with this would be very appreciated!

CodePudding user response:

Express uses precedence when defining routes. I had the following code placed above all of my get routes, therefore overriding them.

app.get("*", function (request, response) {
  response.sendFile(path.resolve(__dirname, "../frontend/build", "index.html"));
});

Solution:

I moved those lines of code to the bottom so that the other routes would take precedence. Now, I get JSON in the response instead of the index.html.

  • Related