0

I am trying to update a resource using patch method. I am completely unable to do so. I am using only Node.js and no React.

My MongoDB schema:
My MongoDB schema

I have to update the desc field. My back-end patch request is working. The code for patch request is:
My patch request at back-end

At Postman, it is working fine:

Postman patch request

You can see the record in the DB is updated:

MongoDB record updated

I need to update it through a form having a text area.

My front-end form

I have attached a function in my front-end JavaScript to the submit button for creating a fetch request.

My front-end JavaScript code

Below is my form in HTML.

My HTML form

Here is how the button is linked with the function:

link between the form submit button and fetch function

This is the error I am getting:

The error

Here is my front-end console:

console

My fetch request for patch JavaScript codes:

await fetch(window.location.href, {
        method: 'PATCH',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          },
        credentials: 'include',  
        body: JSON.stringify({
          desc: abc,
        })
        
      })
        .then((response) =>  {
            console.log(response);
            return response;
        })
        .then((data) => {
            console.log(data);
        })
  };
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
gyanendra
  • 83
  • 7
  • 1
    Hi Gyanendra, good detail on the question but can you include the code/errors/details info copy/pasted strings rather than images. – Matt Sep 23 '22 at 00:55
  • Hello @Matt, I stopped the form from being submitted. I modified my code to `onclick="event.preventDefault(); patched();"` i my html form. I used this JavaScript code. I am getting an Ok response. But while I log my data on console at back end. I received a data like this `{ '{"desc":"test"}': '' }`. I have used the same JavaScript code as specified above. I don't think it's the way I should be receiving data. I need to change it to update record for my mongo dB – gyanendra Sep 23 '22 at 21:55
  • I have my JavaScript code their – gyanendra Sep 23 '22 at 22:01
  • I have solved the problems. I recommend following the article and CodePen link. Article Link [https://gomakethings.com/how-to-send-data-to-an-api-with-the-vanilla-js-fetch-method/] CodePen [https://codepen.io/cferdinandi/pen/xxGaWQY?editors=1112] – gyanendra Sep 24 '22 at 15:56

0 Answers0