AngularJS does not allow data to be deleted in mongodb

Backend code:

var User = require("./models/user");
var express = require('express'),
app = express(),
Account = require("./models/account"),
mongoose = require('mongoose'),
passport = require("passport"),
basicAuth = require('basic-auth'),
bodyParser = require("body-parser"),

LocalStrategy = require("passport-local"),
passportLocalMongoose = require("passport-local-mongoose");  //libraries


mongoose.connect("mongodb://localhost/test");
app.set('view engine', 'ejs'); 
app.use(bodyParser.urlencoded({extended: true}));
app.use(require("express-session")({
secret: "kiss my ass",
resave: false,
saveUninitialized: false
}));

app.use(passport.initialize());
app.use(passport.session());

passport.use(new LocalStrategy(Account.authenticate()));
passport.serializeUser(Account.serializeUser());
passport.deserializeUser(Account.deserializeUser());


// AUTH Routes

//create account success
app.get('/success', function (req, res) {
  res.render('success');
});

// deleteUser form
app.get("/delete", function(req, res, next) {
   res.render("deleteuser"); 
});


app.get("/viewall", function(req, res, next) {
   res.render("viewall"); 
});

//view all User form
app.get('/view', function (req, res) {

console.log('getting all user');
Account.find({})
.exec(function(err, results) {
if(err) {
    res.send('error has occurred');
}else{

    console.log(results);
    res.json(results);
}
});
});

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

console.log('getting one user');
Account.findOne({
    _id:req.params.id
})
.exec(function(err, account) {
if(err) {
    res.send('error occurred');
}else{
    console.log(account);
    res.json(account);
}
})
})

// LOGIN for user
// render login form
app.get("/", function(req, res) {
res.render("login"); 
});

//login for user
//middleware
 app.post("/login", passport.authenticate("local", {
successRedirect: "http://localhost:8082/viewImage.html",
failureRedirect: "http://localhost:8081/error" 
}), function(req, res) {

});

//logout from basicauth
app.get('/logout', function (req, res) {
 res.set('WWW-Authenticate', 'Basic realm=Authenticate Required');
 return res.sendStatus(401);

});

//basicauth for admin login

var auth = function (req, res, next) {
  function unauthorized(res) {
    res.set('WWW-Authenticate', 'Basic realm=Authenticate Required');
    return res.send(401);
  };

  var user = basicAuth(req);

  if (!user || !user.name || !user.pass) {
    return unauthorized(res);
  };

  if (user.name === 'admin' && user.pass === 'admin123') {
    return next();
  } else {
    return unauthorized(res);
  };
 };
//LOGIN for admin
//render login form
app.get("/register", auth, function(req, res) {
 res.render("register"); 


});

// register post
app.post("/register", function(req,res){
Account.register(new Account({username: req.body.username}),  req.body.password, function(err, user){
    if(err){
        console.log(err);

        return res.render('/register');
    }
    passport.authenticate("local")(req, res, function(){
       res.redirect("/success"); 
    });
});
});

app.listen(8081, function () {
console.log('ImageViewer listening on port 8081!');
});

AngularJS code:

$scope.delete = function (data) {
      if (confirm('Do you really want to delete?')){
      $window.location.reload();

        $http['delete']('/viewall/' + data._id).success(function() {
          $scope.users.splice($scope.users.indexOf(data), 1);

        });
      }
    };

HTML code:

<tr ng-repeat="user in users | filter:searchBox | orderBy:'+username'">            
     <td>{{user._id}}</td>
        <td>{{user.username}}</td>
        <td><button class="btn btn-primary" ng-click="delete(user)">Delete</button></td>

Error message received:

DELETE 
XHR 
http://localhost:8081/viewall/5784919136ccb93d0ba78d4b [HTTP/1.1 404 Not  Found 8ms]

However, when accessing the URL http://localhost:8081/viewall/5784919136ccb93d0ba78d4b, the data is successfully retrieved:

{"_id":"5784919136ccb93d0ba78d4b","username":"qs","__v":0}

If anyone can provide assistance regarding the error404 despite being able to retrieve data, it would be greatly appreciated.

Answer №1

No route has been defined for '/viewall/:id' using the DELETE method. To rectify this, you need to include a route that utilizes the DELETE method, as shown below:

app.delete('/viewall/:id',function(req,res){
  // Add the rest of your code here
  // Assuming your model is named Account
  Account.remove({ _id: req.params.id },function(err,doc) {
      if(err) {
         return res.status(400).send({msg: 'An error occurred while attempting to delete the account'});
      }
      return res.status(200).send({msg: 'Account successfully deleted'});
  });
}

Additionally, after successful deletion in your Angular controller, you should reload the page like so:

$http['delete']('/viewall/' + data._id).then(function(response) {
  $scope.users.splice($scope.users.indexOf(data), 1);
  $window.location.reload();
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I use JavaScript to update the content inside HTML tags with a specific string?

I have a situation where I need to replace a string in two different ways Input: Parameters-->string, AnnotationName, input Case 1: And I should input <i>Annotaion</i> as <b>input</b> Output : { displayData: `And I should inp ...

In the JavaScript example provided, do child classes inherit their parent class prototype?

Here's the code I'm working with: class Rectangle { constructor(w, h) { this.w = w; this.h = h; } } Rectangle.prototype.area = function () { return (this.w * this.h); }; class Square extends Rectangle { construct ...

Methods for encoding and decoding special characters using either JavaScript or jQuery

I am looking for a solution to encode and decode various special characters using JavaScript or jQuery... ~!@#$%^&*()_+|}{:"?><,./';[]\=-` I attempted to encode them using the following code snippet... var cT = encodeURI(oM); // ...

Using Formik with MUI Multiple Select

Exploring the world of MUI and Formik, I encountered a challenge with creating a multiple Select in my form. It's my first time working with these tools, so I have a question regarding the implementation. Here's what I've tried based on the ...

What is the method for arranging objects in AngularJS using a custom sorting sequence?

I would like to display an array of object's properties in a custom sorted order. Here is the initial array: $scope.weekDays = [ { "day" : "TUESDAY", "count": 10 }, { ...

Guide to displaying a particular item in Vue 3

Currently, I am embarking on a project that requires the functionality to print a specific element of my webpage. After some research, I came across a mixin/plugin known as VueHtmlToPaper which seems to be the perfect solution for what I need. However, I a ...

Concurrent HTTP Requests - AngularJS

My directive, known as machineForm, includes a dataService: dataService.getMachineTaxesById($scope.machineId).then(function (response) { $scope.machine.machineTaxes = response.data; }); I am using this directive twice simultaneously. <div class= ...

tips for using Node Mailer to send emails without using SMTP

Currently, I am facing an issue with sending emails through nodemailer. Although I have successfully used my gmail account for this purpose in the past, I now wish to switch to using my business email to communicate with clients on a regular basis. The cu ...

Script tag in NextJS

After numerous attempts, I am still struggling with a specific task on this website. The challenge is to insert a script tag that will embed a contact form and newsletter sign-up form, among others, on specific pages of the site. For instance, the contact ...

Tips for transferring information from a controller to a directive in AngularJS using AJAX requests

I want to pass data to a directive once the call is successful. Below is the ajax call from my controller: $scope.items ={ avatar: "" }; $scope.addComment = function(segment) { commentFactory.saveComment($scope.form.comment,segment,0, ...

Prevent vertical scrolling on touch devices when using the Owl Carousel plugin

Is there a way to prevent vertical scrolling on Owl Carousel when dragging it horizontally on touch devices? It currently allows for up and down movement, causing the whole page to jiggle. If anyone has a solution, I can share the JavaScript file. Appreci ...

What is the output of the createRange() function?

I am encountering an issue with my code that is causing the highlighted text to always appear at the end of the page when it pops up. Is there a way to make it show in the middle of the line or below the selected text instead? I have included the current ...

How can a pop-up be positioned to appear in the right bottom corner using jQuery

Is there a way to position a pop-up at the bottom right corner of the window? I have code that centers the pop-up in the window, but I'm looking to place it specifically at the bottom right corner. $(id).css('top', winH - $(id).height()); ...

A windows application developed using either Javascript or Typescript

Can you provide some suggestions for developing Windows applications using Javascript, Typescript, and Node.js? ...

When does the precise execution of the "onEnter" function occur?

Seeking the most efficient method to redirect users from a login/register form if they are already authenticated (and vice-versa). Is it advisable to use onEnter for this purpose? Will that function be executed before the associated controllers? For examp ...

``There seems to be a technical issue with the findOne method in mongoose that

I am facing an issue with my find one method as it is not returning the expected result. Despite trying different approaches, I am unable to get any response or the correct result. This is what I have tried: var ObjectId = require('mongoose').T ...

Attempting to include a new choice on a drop-down menu and ensure its visibility within the drop-down menu

On my journey into the world of web development, I am facing a challenge with adding an option to a dropdown list. Despite pressing the add button to insert "Pasta" as a new option, it is not showing up in the list immediately. However, selecting all optio ...

Can you provide the regular expression that will reject the character "?"

Can you help me verify that my form does not accept double quotes? Validators.pattern(/^(?!").*/g) The current solution is not functioning properly. I want to allow all characters except for double quotes. ...

Tips for creating a test case for retrieving JSON data from a factory in AngularJS

I'm currently working on creating a test case for a factory that returns a JSON response. However, I've encountered the following error: Error: [$injector:unpr] http://errors.angularjs.org/1.4.1/$injector/unpr?p0=serviceProvider%20%3C-%20servic ...

Guide to executing the refresh() function on a kendo-grid using an Angular controller

Currently, I'm experimenting with implementing various recommendations to refresh a kendo-grid, such as the one found on this page. The crux of the matter is that in the HTML code, I have: <div kendo-grid="vm.webapiGrid" options="vm.mainGridOptio ...