Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

Server side 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'); //using engine of ejs file
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 occured');
}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 occured');
}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);
// res.send("<a href='/login'>Show Users</a>");
});

//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!');
});

JS 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>

This is the error i got:

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

But when i run the url of http://localhost:8081/viewall/5784919136ccb93d0ba78d4b and it does give me the data:

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

Anybody can help me? don't know what's with the error404 when i'm able to get the data.

share|improve this question
    
Why are calling this url with the delete method? – Shlomi Haver Jul 12 at 6:56
    
So how should i do it? – Alvin Wee Jul 12 at 7:00
    
Try sending your ajax request with post, and let me know what it returns. – Shlomi Haver Jul 12 at 7:07
    
can you show your server side code (route and controller)? – shaishab roy Jul 12 at 7:17
    
@shaishabroy i posted my server side code already. – Alvin Wee Jul 12 at 7:23
up vote 2 down vote accepted

You have no route for '/viewall/:id' with DELETE verb. So you should add route with DELETE verb. like

app.delete('/viewall/:id',function(req,res){
  // rest of code here
  // assume your model name Account
  Account.remove({ _id: req.params.id },function(err,doc) {
      if(err) {
         return res.status(400).send({msg: 'Error occurred during delete account'});
      }
      return res.status(200).send({msg: 'Successfully deleted'});
  });
}

and you should reload after success in your angular controller. like

$http['delete']('/viewall/' + data._id).then(function(response) {
  $scope.users.splice($scope.users.indexOf(data), 1);
  $window.location.reload();
});
share|improve this answer
    
I tried your code but mongodb do not delete the data. – Alvin Wee Jul 12 at 7:39
    
Able to delete the data on angularjs but the data is still in mongodb. – Alvin Wee Jul 12 at 7:40
    
When refresh the browser, the data is being display out again – Alvin Wee Jul 12 at 7:42
    
updated my answer with remove code @AlvinWee – shaishab roy Jul 12 at 7:43
    
Finally! Its works haha – Alvin Wee Jul 12 at 7:45

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.