Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TypeError: res.json is not a function. I've poured over the similar questions and can't seem to find an answer to my case

I tried to avoid asking another one of the many similar questions on here but I am stumped.
I’m making a bug tracker here. And when i fill out my form and send it off to the server side it gets handled and the bug is created in my database etc.

The issue arises after I save my bug (await bug.save();)
and I send my status and I thought I was also returning my newly created bug back to the client side with a
res.status(201).send(bug);

here is my simple creation endpoint:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 router.post('', auth, async (req, res) => {
 const bug = new Bug({
 ...req.body.bug,
 owner: req.user._id,
 });
 try {
   await bug.save();
   res.status(201).send(bug);
 } catch (err) {
   res.status(400).send(err);
 }
 });

as you can see I am sending my bug object back ( which has various attributes like description, priority, createdBy, etc…)

and here is my fetch call

const saveBug = async function () {
const dataArray = [...new FormData(form)];
const bug = Object.fromEntries(dataArray);
bug.createdBy = activeUser.user.username;

try {
  const res = fetch('', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Accept: 'application/json',
      Authorization: `Bearer ${activeUser.token}`,
    },
    body: JSON.stringify({
      bug: bug,
    }),
  });
  const data = await res.json();
  console.log(data);

  document.querySelector('.bug-form').reset();

  fetchBugs();
} catch (err) {
  console.log(err);
}
};

it seems to be acting like .json() isn’t a function. But I’ve told express to use it in my app with

app.use(express.json());

So I’m just kind of stumped why I can’t seem to find my bug in the client after getting sent back from the server.

>Solution :

You have to use await before the fetch

const res = await fetch('', {
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading