user3650602
user3650602

Reputation: 175

req.body.item undefined - DELETE request express js

I am a beginner to web development, and I am having trouble retrieving the parameters when sending a delete request to my local REST API (written using Express Js). I have already Googled the issue, but most are resolved by using body-parser.

When I return and print the req.body back to the console it comes out as:

{data: "{"Customer":"1"}"}

which seems to look correct? But when I try and retreive

req.body.Customer;

in the routes.js file it comes out as undefined.

Am I missing something really obvious here?

JQuery function to make request

function DeleteItem(){
    let data = {
        Customer: $customerId.text()
    }
    data = JSON.stringify(data);
    $.ajax({
        url: "http://localhost:3000/Customers",
        type: 'DELETE',
        data: {
            data
        },
        success: function(res) {
            console.log(res);
            BuildTable();
        },
        error: function(res) {
            console.log(res);
            alert(res);
        }
    });
}

Routes.js

var express = require("express");
var bodyParser = require("body-parser");
var app = express();

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

var appRouter = function(app) {

app.delete("/Customers", function(req, res) {

    var customer = req.body.Customer;
    console.log(customer);
    res.send(req.body);

});

}

module.exports = appRouter;

Upvotes: 0

Views: 1523

Answers (1)

Giannis Mp
Giannis Mp

Reputation: 1309

First delete the line data = JSON.stringify(data);

then if you need the Customer you should write:

req.body.data.Customer;

or you can change your request like this:

function DeleteItem(){
    let data = {
        Customer: $customerId.text()
    }
    $.ajax({
        url: "http://localhost:3000/Customers",
        type: 'DELETE',
        data: data,
        success: function(res) {
            console.log(res);
            BuildTable();
        },
        error: function(res) {
            console.log(res);
            alert(res);
        }
    });
}

Right now you are creating a new object data and assigning the object you created before to it.

Upvotes: 4

Related Questions