Chameen
Chameen

Reputation: 25

How to use fetch to send a variable to a GET request?

I am having an issue with using fetch to send an id which is then sent to a get request in the backend which performs a function.

The aim of the function is to delete the element from the JSON file which is entered into the input box in the front end.

However, when I do this, I get an error saying the route for the function is not found:
GET http://localhost:3000/delete 404 (Not Found)

This is the code for the /delete route:

app.get('/delete/:id', function (req, res) {

    var id = req.params.id;

    for (var i = 0; i < tasksArray.length; i++) {
        if(tasksArray[i].id == id) {
            tasksArray.splice(i, 1);
        }
    }
    res.json(tasksArray);
    var json = JSON.stringify(tasksArray);
    fs.writeFileSync("toDoList.json", json);

});

This is the code for the front end with fetch:

function deleteElement() {

      var id = document.getElementById("deleteId").value;


      var url = "http://localhost:3000/delete";

        fetch(url, {
            method: 'GET',
            url: `/delete/${id}`,
            headers: {
                'Content-Type': 'application/json'
            }
        });
}

Any help is appreciated.

Upvotes: 0

Views: 69

Answers (1)

Yusuf
Yusuf

Reputation: 352

You were not using id in the url.

function deleteElement() {
  var id = document.getElementById("deleteId").value;
  var url = "http://localhost:3000/delete/" + id;
  fetch(url, {
    // removed url as it's defined in fetch's first arguments.
    method: 'GET',
    headers: {
      'Content-Type': 'application/json'
    }
  });


}

Upvotes: 1

Related Questions