Cannot delete article in Node/JavaScript app - node.js

I want to delete my articles. The code should be working but I couldn't understand that it doesn't work. I have created a js file to send delete issue (with ajax)
This is my delete.js:
$(document).ready(function(){
$('.delete-article').on('click', function(e){
$target = $(e.target);
const id = $target.attr('data-id');
$.ajax({
type:'DELETE',
url: '/metin/'+id,
success: function(response){
alert('Konu Siliniyor');
window.location.href='/';
},
error: function(err){
console.log(err);
}
});
});
});
This is my app.js delete route:
app.delete('/metin/:id', function(req, res){
let query = {_id: req.params.id};
Metin.remove(query, function(err){
if(err) {
console.error(err);
} else {
res.send('Success');
}
});
});
This is my article.pug:
a.button.btn.btn-danger.delete-article(href='#', data-id=metin._id) Delete
Where do I missing a code? I couldn't find it. What can I check next?

Related

ejs file not rendering with res.render when I call the server side js method from client side js

I am new to node.js and trying to call an ejs file from server-side js. I am calling both the post and get methods from the client js file. Below is my code.
Client-side js:
function playerlist(){
const button = document.getElementById('playerselection');
//const data={selectedplayers:window.players};
button.addEventListener('click', function() {
console.log(players);
fetch('/FantasyTeam', {method: 'POST',
body: JSON.stringify(players),
headers: {'Content-Type':'application/json'},
})
.then(function(response) {
if(response.ok) {
CallGetMethod();
return;
}
throw new Error('Request failed.');
})
.catch(function(error) {
console.log(error);
});
});
}
function CallGetMethod(){
console.log('Inside CallGetMethod');
fetch('/FantasyTeam', {method: 'GET'})
.then(function(response) {
if(response.ok) {
console.log('Inside response');
return ;
}
throw new Error('Request failed.');
})
.catch(function(error) {
console.log(error);
});
}
**Server-side js:**
app.post('/FantasyTeam', (req, res) => {
const playerlist = req.body;
console.log(playerlist);
sql.connect(dbConfig, {
useNewUrlParser: true
}).then(() => {
// create Request object
console.log("Connected!");
var request = new sql.Request();
//Insert query to FantasyTeam Table with selected players.
request.query("INSERT Query").then(function (err, result)
{
console.log('record added to db');
}).catch(err => {
console.log('Could not insert the record to DB. Exiting now...', err);
process.exit();
});
}
res.sendStatus(201);
}).catch(err => {
console.log('Could not connect to the database. Exiting now...', err);
process.exit();
});
});
app.get('/FantasyTeam', (req, res) => {
// connect to your database
sql.connect(dbConfig, {
useNewUrlParser: true
}).then(() => {
// create Request object
var request = new sql.Request();
request.query("select query"), function (err, result)
{
console.log('records fetched from DB');
//res.send(result);
//res.render(path.resolve(__dirname + "/views/FantasyTeam"),{result});
res.render('FantasyTeam.ejs', { result });
//res.render('FantasyTeam.ejs', { result });
console.log(result.recordset.length);
});
}).catch(err => {
console.log('Could not connect to the database. Exiting now...', err);
process.exit();
});
}) ;
I tried multiple ways to render the FantasyTeam.ejs file. But couldn't succeed.There is no error in code, except that ejs file is not redered. Appreciate any help in this regard.
At first you have set view engine on your node application. Then second step create a views folder on the application root and then create a pages folder in views folder then create all template in your pages folder. views folder needs to be static. finally you can render template from pages folder in views directory. See my example. For more information visit to ejs doc: https://ejs.co/#docs
const express = require('express');
const app = express()
const router = express.Router()
// Setup View Engine and set static folder
app.use(express.static('public'))
app.set('view engine','ejs')
app.set('views','views')
//Controller
router.get('/example',(req,res,next)=>{
res.render('pages/index.ejs',{You Data})
})

why does my express route work for "/" but not "/:id"?

I was troubleshooting why my route wasn't working and i came across this.
In my ./routes/jobs.js,
router.delete("/:id", (req, res) => {
Job.findByIdAndDelete(req.params.id, (err, job) => {
if (!err) {
res.json({ msg: "job deleted"});
} else {
console.log(err);
}
});
});
When i tested on postman, Delete - http://localhost:5000/dashboard/60b9405e1ea
Would return the id only 60b9405e1ea and not delete the db job.
I changed my route to "/" and tested it out. using http://localhost:5000/dashboard in postman.
router.delete("/", (req, res) => {
Job.findByIdAndDelete(req.params.id, (err, job) => {
if (!err) {
res.json({ msg: "job deleted"});
} else {
console.log(err);
}
});
It executed the delete request with {msg: "job deleted"}. (Obviously didnt delete db job since no id was given).
Keep in mind in my server.js im using,
app.use("/dashboard", require("./routes/jobs"));
Any help would be appreciated on why /:id is not being executed
As you are getting the id in the console, it's the problem with the query you make.
Try any of these,
Model.remove({ _id: req.body.id }, function(err) {
if (!err) {
message.type = 'notification!';
}
else {
message.type = 'error';
}
});
or
Model.findOneAndRemove({id: req.params.id}, function(err){
});
or a traditional approach:
Model.findById(id, function (err, doc) {
if (err) {
// handle error
}
doc.remove(callback); //Removes the document
})

Why my nodejs requests are slow?

Im new in nodejs, and Im trying to learn by creating an app that has a list of users, that I can add and remove those users. Im using angularjs in frontend to send request to nodejs and after that to mongodb. The problem is that, if I click a lot of times in the button "adduser" a lot of times, my app goes slow.
To interact to mongodb I use:
app.get('/users',function (req, res) {
mongoose.model('Usuario').find(function (err, list) {
res.send(list);
});
});
app.post('/addusuario', function (req,res) {
var usuario = new Usuario(req.body);
usuario.save(function (err) {
if (err) {
console.log(err);
} else {
console.log('Usuario salvo com sucesso');
}
}); });
app.delete('/delusuario/:id', function (req, res) {
var id = req.params.id;
mongoose.model('Usuario').findByIdAndRemove(id , function(err) {
if(err) {
console.log(err);
} else {
console.log('Usuario removido com sucesso!');
}
});
});
Im my angularapp:
app.controller('AppCtrl', function($scope, $http, Data) {
function reload() {
Data.get('users').then(function(data){
$scope.usuarios = data;
console.log(data);
});
};
$scope.addUsuario = function(usuario) {
Data.post('/addusuario', usuario);
reload();
};
$scope.deletarUsuario = function(id) {
Data.delete("/delusuario/"+id).then(function(result) {
});
reload();
};
reload();
});
I dont know why it is becaming slow after I click to add user more than 3 times..
What I see in your code that you are not sending an response back to the user, you should do something after insert or delete in the database. res.end();
You should rewrite your code in the following way:
app.get('/users',function (req, res) {
mongoose.model('Usuario').find(function (err, list) {
res.send(list);
});
});
app.post('/addusuario', function (req,res) {
var usuario = new Usuario(req.body);
usuario.save(function (err) {
if (err) {
console.log(err);
res.json({err: err});
} else {
res.json({ok: true});
console.log('Usuario salvo com sucesso');
}
}); });
app.delete('/delusuario/:id', function (req, res) {
var id = req.params.id;
mongoose.model('Usuario').findByIdAndRemove(id , function(err) {
if(err) {
console.log(err);
res.json({err: err});
} else {
res.json({ok: true});
console.log('Usuario removido com sucesso!');
}
});
});
You block the stack by not returning the response to the client. And this is most probably the cause of your slow request.

MEAN Stack CRUD update 404 error

Heads up, noob coming through. Trying to build a MEAN stack todo list. So far I've gotten everything to work except for the update option. What I've done is set up the application so that it prompts the user to write in the item they want to update. So say they add the item 'ddd.' The update button would then appear beside the item, and then the user would be given a prompt, asking them to enter the new item. The problem is whenever the user does in fact enter the new item to replace the old, nothing happens, and I instead get a 404 error in the command prompt. Any help would be much appreciated. Below you'll find my controller, routes, index.html
routes/api
var Todo = require('./models/todo');
module.exports = function(app) {
// api ---------------------------------------------------------------------
// get all todos
app.get('/api/todos', function(req, res) {
// use mongoose to get all todos in the database
Todo.find(function(err, todos) {
// if there is an error retrieving, send the error. nothing after res.send(err) will execute
if (err)
res.send(err)
res.json(todos); // return all todos in JSON format
});
});
// create todo and send back all todos after creation
app.post('/api/todos', function(req, res) {
// create a todo, information comes from AJAX request from Angular
Todo.create({
text : req.body.text,
done : false
}, function(err, todo) {
if (err)
res.send(err);
// get and return all the todos after you create another
Todo.find(function(err, todos) {
if (err)
res.send(err)
res.json(todos);
});
});
});
// delete a todo
app.delete('/api/todos/:todo_id', function(req, res) {
Todo.remove({
_id : req.params.todo_id
}, function(err, todo) {
if (err)
res.send(err);
// get and return all the todos after you create another
Todo.find(function(err, todos) {
if (err)
res.send(err)
res.json(todos);
});
});
});
//update to do
app.put('/api/todos/_id', function(req, res) {
Todo.findById(req.params._id, function(err, todos){
todo.text = req.body.text;
console.log(todos);
todos.save(function() {
if (!err) {
res.send(todos);
} else if (err) {
res.send(err);
}
});
});
});
// application -------------------------------------------------------------
app.get('*', function(req, res) {
res.sendfile('./public/index.html'); // load the single view file (angular will handle the page changes on the front-end)
});
};
controller
var baselTodo = angular.module('baselTodo', []);
function mainController($scope, $http) {
$scope.formData = {};
// when landing on the page, get all todos and show them
$http.get('/api/todos')
.success(function(data) {
$scope.todos = data;
})
.error(function(data) {
console.log('Error: ' + data);
});
// when submitting the add form, send the text to the node API
$scope.createTodo = function() {
$http.post('/api/todos', $scope.formData)
.success(function(data) {
$('input').val('');
$scope.todos = data;
})
.error(function(data) {
console.log('Error: ' + data);
});
};
// delete a todo after checking it
$scope.deleteTodo = function(id) {
$http.delete('/api/todos/' + id)
.success(function(data) {
$scope.todos = data;
})
.error(function(data) {
console.log('Error: ' + data);
});
};
$scope.updateTodo = function(id) {
$scope.newItem = prompt("Please enter your new item:", "");
$http.put('/api/todos/' + id, {formData: $scope.newItem}).success(function(data) {
$scope.todos = data;
});
$http.get('/api/todos').success(function(data) {
$scope.todos = data;
});
};
};
It looks like, in your routes api:
app.put('/api/todos/_id', function(req, res) {
You forgot the colon in the path, therefore you can't access that variable. Try:
app.put('/api/todos/:_id', function(req, res) {

Express Route stops working after a set amount of Angularjs Post

I'm having some trouble getting AngularJS, Express and MongoDB to work together. I'm still new to all three of these and trying to make a simple 'to do' app and toggle a check button to mark something complete. I able to execute a function on the angular side that will do a $http 'POST' to an express route that ultimately updates a MongoDB record. I am able to do this 6 times before it stops working. I can see in the inspector console that the function is still being called, but somewhere between the $http 'POST' and executing the route, it doesn't register it anymore. I no longer see console.log activity on my Express server from the route.
Here is my toDoController.js
toDoApp.controller('ToDoController', function ToDoController($scope, $http, itemsData) {
... other functions
$scope.toggleToDo = function(item) {
console.log('updateToDo()');
console.log(item);
$http({
method: 'POST',
url: '/todolist/toggle_to_do',
data: item
}).
success(function(data, status, headers, config) {
console.log('success post');
}).
error(function(data, status, headers, config) {
console.log(data);
console.log(status);
console.log(headers);
console.log(config);
});
}
}
Express app.js route
app.post('/todolist/toggle_to_do', todolist.toggleToDo);
Express route.js
var MongoClient = require('mongodb').MongoClient;
var ObjectID = require('mongodb').ObjectID; // used to create ObjectID when looking for the record
var collection
var database
// Connect to Database ------------------------------------------------
MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db){
if(err) throw err;
console.log('\033[96m + \033[39m connected to mongodb');
collection = db.collection('to_do_list');
database = db;
}
);
// update record
exports.toggleToDo = function(req, res) {
console.log("-toogle 'To Do item' completed status");
console.log(req.body.completed);
console.log(req.body._id);
collection.update({
_id: new ObjectID(req.body._id)
},
{
$set: {
completed: req.body.completed
}
},
function(err) {
if(err) console.warn("Could not write to DB");
else console.log("Item successfully updated!");
}
);
};
Any help would be appreciated! Thanks!
Looks like I didn't end my response.
res.end();
exports.toggleToDo = function(req, res) {
console.log("-toogle 'To Do item' completed status");
console.log(req.body.completed);
console.log(req.body._id);
collection.update({
_id: new ObjectID(req.body._id)
},
{
$set: {
completed: req.body.completed
}
},
function(err) {
if(err) console.warn("Could not write to DB");
else console.log("Item successfully updated!");
}
);
res.end();
};

Resources