Lukasz Migut
Lukasz Migut

Reputation: 192

Express 4.0 and Mysql prblem with PUT and DELETE request

I'm trying to develop a simple API for a todo app. I have a problem with PUT requests: when I use postman (chrome app for REST) the request is long and the node console displays [object, object] not the value from the request. Also, the mysql database is not updated.

Route:

router.route('/todo/:todo_id')
.put(function(req, res) {
    var input = JSON.parse(JSON.stringify(req.params));
    var id = req.params.id;
    var data = {
        todo_title: input.title,
        todo_description: input.description
    };
    db.query('UPDATE task SET ? WHERE todo_id = ?', [data,id], function(err, result) {
        if(err) throw err;
        console.log("Dane zostały uaktualnione: " + result);
    });
});

I have problem with DELETE too:

.delete(function(req, res) {
    db.query('DELETE FROM task WHERE todo_id=?', [req.params.todo_id], function(err, result) {
        if (err) throw err;
        console.log('usunieto: ' +result);
    });
});

Template:

<h1>Edit</h1>
    <% items.forEach(function(item) { %>
    <form action="/api/todo/<%= item.todo_id %>" method="PUT">      
        <label for="title">Nazwa zadania</lablel><br>
        <input name="title" type="text" value="<%= item.todo_title %>"><br>
        <label for="description">Opis zadania</label><br>
        <textarea name="description" value="<%= item.todo_description %>"></textarea><br>
        <input type="submit" value="SSij">
    <% }); %>
    </form>

Where is the problem?

Upvotes: 0

Views: 1122

Answers (1)

mscdex
mscdex

Reputation: 106698

The problem is that HTML forms only support GET and POST.

There's at least a couple of solutions to this:

  • Since you're using Express, there is a method-override middleware that allows you to POST the form instead, and then inside your form you have a hidden input field or query parameter or custom logic that designates the real HTTP verb to use for routing purposes.

  • Use XMLHTTPRequest to send the form instead, which supports GET, POST, PUT, and DELETE.

Upvotes: 1

Related Questions