0

I am working with React, Express, PostgreSQL, Node, and the Fetch API. When I try to run a "GET" request (within a try block) to get data from my database, the request fails (and enters the catch block) with the following error:

Unexpected token < in JSON at position 0

Here is the failing code that I have on the front end:

const getRequests = async () => {
    try {
      const responseInfo = await fetch("/api/advice-requests", {
        headers: { "Accept": "application/json" },
      });

      if (responseInfo.status === 200) {
        console.log("200 running"); // This is logged to the console.

        const data = await responseInfo.json();

        console.log("data :", data); // This is NOT logged to the console. It fails.

        setAdviceRequests(data.requests);
        setResponses(data.responses);

        return;
      }
      
    } catch (error_o) {

      // The UI is updated with the text of the below error

      setError(
        "Something went wrong on our end. We are looking into how we can improve..."
      );

      return;
    }
  };

Here is some of my server code (there is more, but it is not relevant), including some changes I made that worked to solve this problem for other people.

const adviceRequests = require("./controllers/adviceRequests");
const express = require("express");
const app = express();
const cors = require("cors");

app.use(express.json());
app.use(cors());
app.options("*", cors());

if (process.env.NODE_ENV === "production") {
  app.use(express.static(path.join(__dirname, "../build")));
  app.get("/*", (req, res) => {
    res.sendFile(path.join(__dirname, "../build", "index.html"));
  });
}

app.get("/api/advice-requests", adviceRequests.getAll);

app.listen(PORT, () => {
  console.log(`SERVER RUNNING ON ${PORT}.`);
});

Lastly, here is the adviceRequests.getAll function:

getAll: async (req, res) => {
    const db = req.app.get("db");

    try {
      let requests = await db.requests.getAll(req.session.user.id);
      let responses = await db.responses.getAll([req.session.user.id]);

      return res.status(200).send([requests, responses]);

    } catch (error) {

      return res.status(500).send({
        message:
          "Something went wrong on our end. We are looking into how we can improve.",
          error,
      });
    }
  },

A bit more information:

  • The code works just fine when I run it locally
  • Even on the live server, I can successfully run several POST requests for authentication and adding requests. I just cannot get them.
  • I have done quite a bit of research into this and am posting my own as a last resort. Nothing that has worked for other people has worked for me so far.

1 Answer 1

1

Everytime I have had this "Unexpected token < in JSON at position 0" it was because i was trying to parse an html plain response as if it was a json. Note that every html file starts with a <.

I suggest you change this console.log("200 running"); with a console.log(responseInfo);, that way you'll notice if the response is a json or not.

From what I see, the problem might be the order in which the app.get are defined. Note that express serves first come first served, so since you have already defined an app.get("/*"), everything will be served by that route. Also note that you are sending back an index.html, which matches the issue shown in the frontend.

Sign up to request clarification or add additional context in comments.

1 Comment

It was the order!! Thank you so much!! I have spent around 8 hours trying different solutions, and moving the app.get("/*") below the other requests is all it took. I appreciate you taking the time to read and answer that question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.