Home > Software design >  fecth api not posting data to nodeserver
fecth api not posting data to nodeserver

Time:02-11

i have a node backend set up, when i send a get request, it works perfectly, but when i send a post request it doesn't send the data to the backend. Here is my code:

  fetch("http://localhost:3000/", { method: "POST",body:{"title":title.value,"content":content.value}})
    .then((res) => res.json())
    .then((data) => {
      console.log(data);
    });

i have even tried sending it through the formdata object it is still not working:

  const formdata = new FormData();
    formdata.append("title",title.value)
    formdata.append("content",content.value)


    fetch("http://localhost:3000/", { method: "POST",body:formdata})
      .then((res) => res.json())
      .then((data) => {
        console.log(data);
      });

this is the console.log: enter image description here

this is the backend:

//crud applications
app.post("/", async (req, res) => {
  const { title, content } = req.body;

  try {
    const newPost = await postModel.create({ title, content });
    res.json(newPost);
  } catch (error) {
    res.status(500).send(error);
  }
});

CodePudding user response:

instead of using fetch, use Axios. import it in your HTML with this CDN <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

and then use this code it should work:

  const data = {
      title: title.value,
      content: content.value,
    };
    axios.post("http://localhost:3000/", data).then((response) => {
      const result = response.data;
      console.log(result);
     
    });
  • Related