Home>

We are developing API using express.
Currently, modify the data in req.body (JSON assumption)
The method of app.patch has been created and
The operation check in insomnia etc. has been completed.

app.patch ("/ update /: id", async function (req, res) {
   ...
});

In addition, the post that registers the data of req.body is also created in the same way.
The communication is complete.

app.post ("/ create", async function (req, res) {
   ...
});
<script>
          let xhr = new XMLHttpRequest ();
            let exp = new Object ();
     exp = {
        JSON data
     };
        let result = document.getElementById ('result');
        xhr.open ("post", "http: // localhost: 3000/create", true);
        xhr.setRequestHeader ('content-type','application/json;charset = utf-8');
        x.send (JSON.stringify (exp));
</script>

I searched several sites and made the following corrections.
As far as the log on the server side is seen, in the first place
It seems that the above js method has not been reached.

<script>
        xhr.open ("patch", "http: // localhost: 3000/update", true);
</script>

If patch → put, it works, but
I want app.patch to work.
Let me ask you two questions.

① Is there a way to connect to app.patch with XMLHttpRequest?
(2) Please tell me if there is a way to connect to app.patch using js without using XMLHttpRequest.

  • Answer # 1

    XMLHttpRequest is not used at this time
    Let's use fetch

    (async () =>{
        const response = await fetch ('http: // localhost: 3000/update',
            {'method':'patch',
              body: JSON.stringify (data),
              headers: {
                'Content-Type':' application/json'
              },
            }
        );
        console.log (response);
    }) ();

    If it is not the same domain, other settings are required.

Related articles