0

How to handle Delete Query When id not available in App.delete method not giving error .in both case show success. if id not available then it should output id not available to delete task . same case for get by id method . if id is available it working right . if id not available it did not show error

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mysql = require('mysql');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));

// connection configurations
const mc = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '',
    database: '1234'
});

// connect to database
mc.connect();

// default route
app.get('/', function (req, res) {
    return res.send({ error: true, message: 'hello' })
});

// Retrieve all todos 
app.get('/todos', function (req, res) {
    mc.query('SELECT * FROM tasks', function (error, results, fields) {
        if (error) throw error;
        return res.send({ error: false, data: results, message: 'Todos list.' });
    });
});

// Search for todos with ‘bug’ in their name
app.get('/todos/search/:keyword', function (req, res) {
    let keyword = req.params.keyword;
    mc.query("SELECT * FROM tasks WHERE task LIKE ? ", ['%' + keyword + '%'], function (error, results, fields) {
        if (error) throw error;
        return res.send({ error: false, data: results, message: 'Todos search list.' });
    });
});

// Retrieve todo with id 
app.get('/todo/:id', function (req, res) {

    let task_id = req.params.id;

    mc.query('SELECT * FROM tasks where id=?', task_id, function (error, results, fields) {
        if (error) throw error;
        return res.send({ error: false, data: results[0], message: 'Todos list.' });
    });

});

// Add a new todo  
app.post('/todo', function (req, res) {

    let task = req.body.task;

    if (!task) {
        return res.status(400).send({ error:true, message: 'Please provide task' });
    }

    mc.query("INSERT INTO tasks SET ? ", { task: task }, function (error, results, fields) {
        if (error) throw error;
        return res.send({ error: false, data: results, message: 'New task has been created successfully.' });
    });
});

//  Update todo with id
app.put('/todo', function (req, res) {

    let task_id = req.body.task_id;
    let task = req.body.task;

    if (!task_id || !task) {
        return res.status(400).send({ error: task, message: 'Please provide task and task_id' });
    }

    mc.query("UPDATE tasks SET task = ? WHERE id = ?", [task, task_id], function (error, results, fields) {
        if (error) throw error;
        return res.send({ error: false, data: results, message: 'Task has been updated successfully.' });
    });
});

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

    let task_id = req.params.id;

    if (!task_id) {
        return res.status(400).send({ error: true, message: 'Please provide text_id' });
    }
    mc.query('DELETE FROM tasks WHERE id = ?', task_id, function (error, results, fields) {
        if (error) throw error;
        return res.send({ error: false, data: results, message: 'text has been Deleted successfully.' });
    });
});

// all other requests redirect to 404
app.all("*", function (req, res) {
    return res.status(404).send('page not found')
});

// port must be set to 8080 because incoming http requests are routed from port 80 to port 8080
app.listen(8080, function () {
    console.log('Node app is running on port 8080');
});

// allows "grunt dev" to create a development server with livereload
//module.exports = app;
1
  • Small advice about code in the question. I suggest you remove unrelated parts of the code for clarity about what you're asking. Commented Aug 11, 2018 at 0:36

1 Answer 1

1

You have to define the param as optional.

Express uses path-to-regexp for matching the route paths; see the path-to-regexp documentation for all the possibilities in defining route paths. Express Route Tester is a handy tool for testing basic Express routes, although it does not support pattern matching.

https://expressjs.com/en/guide/routing.html

Works for /todo and /todo/{id},

route - /todo/:id*?

 //  Delete todo
app.delete('/todo/:id*?', function (req, res) {


});
Sign up to request clarification or add additional context in comments.

2 Comments

Sorry @Roy i can not get it ? i follow this link arjunphp.com/creating-restful-api-express-js-node-js-mysql
Each routing register with an endpoint in your code: GET /todo/:id == /todo/1, DELETE /todo/:id' == /todo/1. when you send a request with type DELETE to the endpoint without param the code doesn't know how to handle it, because the param is mandatory and part of the path of route

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.