简体   繁体   中英

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:

 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.

You have to use await before the fetch

const res = await fetch('', {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM