Next.js Discord

Discord Forum

Error - Error: Unexpected token '<', "<!DOCTYPE "... is not valid JSON

Unanswered
Ragdoll posted this in #help-forum
Open in Discord
RagdollOP
I am fetching the all blogs list from the blog api which is returning a valid json acc to me.
Note that this error occur occasionally not everytime ,
This is the controller
exports.blog_list = asyncHandler(async (req, res) => {
  const allBlogs = await Blog.find().sort({ createdAt: -1 });
  res.json(allBlogs);
});


React Component-
async function getData(): Promise<Blog[]> {
  const res = await fetch("http://localhost:3001/api/blogs/", {
    cache: "no-store",
  });
  const blogs = await res.json();
  return blogs;
}

type Props = {};
async function Manage({}: Props) {

  const blogs = await getData();
  return (
    <div>
      {blogs.map((b: Blog) => (
        <BlogOption blog={b} key={b._id} />
      ))}
    </div>
  );
}


- The mongoDB cluster is currently connected .

10 Replies

@@ts-ignore try to do `await res.text()` and then see what is the output
RagdollOP
Now there are few issues like blogs.map is not a function and type formatting too
@@ts-ignore do blogs?.map
RagdollOP
error TypeError: blogs?.map is not a function
I think res.text() is not returning something iterable
@Ragdoll `error TypeError: blogs?.map is not a function` I think res.text() is not returning something iterable
comment out that map for sometime and just take a look at the content of console.log
@@ts-ignore comment out that map for sometime and just take a look at the content of console.log
RagdollOP
TypeError [ERR_INVALID_STATE]: Invalid state: ReadableStream is already closed

async function getData(): Promise<Blog[]> {
  const res = await fetch("http://localhost:3001/api/blogs/", {
    cache: "no-store",
  });
  const blogs = await res.text();
  console.log("here ", blogs);
  return blogs;
}
@@ts-ignore try to visit that route in browser and see what is returned
RagdollOP
the api is hosted locally and the issue is recurring timeout from mongodb
MongoNetworkError: Socket connection timeout , though I have increased the timeout time
@@ts-ignore well then you need to figure out this
RagdollOP
yes , thank you