space_jam23
space_jam23

Reputation: 21

NodeJS (Express) - app.delete route not working

Working on understanding CRUD basics with setting up simple routes from my HTML5 doc to Postgres database. My GET and POST buttons are working but my DELETE is not deleting from my database. I realize the routes all look very similar (and tried renaming them to see if it would hit the callback function that is linked to the database, but it didn't work). Can anyone tell me why my HTML5 form is not working with my route to reach the database for DELETE? Thanks!

I will only include the code I'm referring to as I have all the other code working well. Starting with showing the crappy HTML first, then the index.js with the routes, and then the queries.js with the database queries. ( ////// seperate the documents where the code is pulled :) )

 <h1>Let's DELETE ONE Human</h1>
    <form action="/users/:id" method="delete">
        ID:<input type="number" name="id">
        <input type="submit" name="">
    </form>

    /////////////////////////////////////////////////////////////////

    app.get('/', (request, response) => {
      response.sendFile(path.join(__dirname + '/html/homepage.html'))
    }, db.getUsers)

    app.get('/newHuman.html', (request, response) => {
      response.sendFile(path.join(__dirname + '/html/newHuman.html'))
    })
    app.get('/users', db.getUsers)
    app.get('/users/:id', db.getUserById)
    app.post('/users', db.createUser)
    app.put('/users/:id', db.updateUser)
    app.delete('/users/:id', db.deleteUser)

    app.listen(port, () => {
      console.log(`App running on port ${port}.`)
    })
  ////////////////////////////////////////////////////////////////////////

const deleteUser = (request, response) => {
      const id = parseInt(request.query.id)

      pool.query('DELETE FROM users WHERE id = $1', [id], (error, results) => {
        if (error) {
          throw error
        }
        response.status(200).send(`User deleted with ID: ${id}`)
      })
    }

TL;DR
How can I send to the correct route (even with just POSTing twice) from my HTML when the app.delete and app.put have the exact same route? Tried renaming route, didn't work but I know you shouldn't have to rename for it to work. Here are routes:

app.put('/users/:id', db.updateUser) app.delete('/users/:id', db.deleteUser)

Upvotes: 1

Views: 4837

Answers (2)

Rohit Kashyap
Rohit Kashyap

Reputation: 1592

Another easier way of doing this is using a npm module called method-override.

In your main entry point file for your server, add the following lines:

const express = require('express');
const app = express();
const methodOverride = require('method-override');
app.use(methodOverride('_method'));

In your HTML form, you can now use PUT or DELETE requests easily: For example:

    <h1>Let's DELETE ONE Human</h1>
<form id='myFormId' action="/users/:id?_method=DELETE" method="delete">
    ID:<input type="number" name="id" id='deleteId'>
    <input type="submit" name="">
</form>

Notice the action attribute of the form, all you have to do now is add that simple line and you are done!

Upvotes: 1

Shams Nahid
Shams Nahid

Reputation: 6559

HTML form method only supports GET and POST method.

Either you have to use GET or POST or you can use ajax or some library like request or axios to make the DELETE request.

For example, if you use axios, try the following code.

Ignore importing jQuery and axios, if you already imported them.

<!-- import jQuery -->
<script
  src="https://code.jquery.com/jquery-3.3.1.js"
  integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
  crossorigin="anonymous"></script>
<!-- import axios -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>


<h1>Let's DELETE ONE Human</h1>
<form id='myFormId' action="/users/:id" method="delete">
    ID:<input type="number" name="id" id='deleteId'>
    <input type="submit" name="">
</form>


<script>
    $( document ).ready(function() {
        const myForm = $('#myFormId');
        myForm.submit((event) => {
            event.preventDefault();
            const id = $('#deleteId').val();
            const url = `/users/${id}`;
            axios.delete(url)
                .then(function (response) {
                    console.log(response);
                })
                .catch(function (error) {
                    console.log(error);
                });
        });
    });
</script>

Upvotes: 1

Related Questions