I have been searching all over for how to do this - I am trying to redirect after a DELETE request is made - here is the code I am using WITHOUT THE REDIRECT:
exports.remove = function(req, res) {
var postId = req.params.id;
Post.remove({ _id: postId }, function(err) {
if (!err) {
console.log('notification!');
res.send(200);
}
else {
console.log('error in the remove function');
res.send(400);
}
});
};
remove gets called when an item (a post) is deleted. Everything works fine (I had to use res.send(200) to get it to not hang on the delete request) - but now I am having trouble redirecting. If I use res.redirect('/forum') inside the remove function, like this:
exports.remove = function(req, res) {
var postId = req.params.id;
Post.remove({ _id: postId }, function(err) {
if (!err) {
console.log('notification!');
res.send(200);
}
else {
console.log('error in the remove function');
res.send(400);
}
res.redirect('/forum');
});
};
It registers the redirect as a DELETE request that is trying to delete /forum, like this:
DELETE http://localhost:9000/forum 404 Not Found 4ms
All I am trying to do is refresh the page so that the list of posts is updated after the delete. Can anyone help?
I know this is late, but for anyone who sees this later, you can also manually reset the HTTP method to GET which should also work
exports.remove = function(req, res) {
var postId = req.params.id;
Post.remove({ _id: postId }, function(err) {
if (!err) {
console.log('notification!');
res.send(200);
}
else {
console.log('error in the remove function');
res.send(400);
}
//Set HTTP method to GET
req.method = 'GET'
res.redirect('/forum');
});
};
#ewizard 's solution is great if you can fix this on the front end. However, if you want to fix this on the back end, you can add an optional Status Code argument to res.redirect like so:
res.redirect(303, "/forum");
This redirects for "Undefined Reason" which will default to a GET redirect.
See this SO post for more info.
I got it working on my Angular side with $window.location.href = '/forum'; - just put it in the success function of the $http request that is part of the delete function that gets executed when the "Delete" button is clicked.
Related
I have a problem right now that I can't solve by myself. I assume you know more here. I'm just getting started.
By using the following code I'm getting a list of customers:
app.get("/customers", customers.findAll);
I wanted to add authentication. But now I don't know how to execute "customers.findAll" and get the value as JSON.
app.get("/customers", verifyToken, (req, res) => {
jwt.verify(req.token, 'justAtest, (err, authData) => {
if (err) {
res.sendStatus(403);
} else {
// execute customers.findAll
}
});
});
Customers is integrated via a requirement
const customers = require("../controllers/customer.controller.js");
The contents are as follows:
exports.findAll = (req, res) => {
Customer.getAll((err, data) => {
if (err)
res.status(500).send({
message:
err.message || "Some error occurred while retrieving customers."
});
else res.send(data);
});
};
Do you have any ideas?
Thank you in advance.
Grettings
Rok
You achieve that using something called "middleware". Explore it since it is very important.
Basically :
app.get("/customers", verifyToken,customers.findAll);
Wherre verify token is a funtion that has 3 parameters: req, res and 3rd one called "next".
So your verify token function would look something like:
(req, res,next) => {
jwt.verify(req.token, 'justAtest, (err, authData) => {
if (err) {
res.sendStatus(403);
} else {
next();
}
});
}
I took it from your snippet. Basically if you want to jump to customeeers.finalAll, just call "next" and it jumps to next function :D.
I am currently trying to create a client-side reroute for users that are invalid. The server validates if the user has access to the current page and if not it returns {data: 'invalid'} in the success callback of the ajax call I check this value with the following:
if (data.status === 'invalid') {
window.location.href = domain + '/login';
return false;
}
This works sometimes but other times I receive the following browser alert message:
RequestAbortedError: Request aborted
I have attempted to swap out window.location.href with window.location.replace() and top.location.href but neither resolved the issue. I can see that the server is processing the information correctly and returning {data: 'invalid'} but as soon as it tries to run the line window.location.href I receive this error. I have an image below if it helps.
When "OK" is clicked the page does redirect to the appropriate page. The end result is happening as expected but I cannot resolve the error.
UPDATE INCLUDING SERVER SIDE CODE
function authentication (req, res, next) {
console.log('entered');
if (typeof req.rsaConPortal.email !== 'undefined') { // Check if session exists
console.log('passed 1');
User.findOne({ "user.email": req.rsaConPortal.email, "user.status”: req.resConPortal.status}, function (err, user) {
if (!user) {
console.log('failed 2');
req.rsaConPortal.reset();
res.send({status: 'invalid'});
} else {
console.log('passed 2');
req.rsaConPortal.email = user.user.email;
req.rsaConPortal.id = user._id;
req.rsaConPortal.status = user.user.status;
next();
}
});
} else {
console.log('failed 1');
res.send({status: 'invalid'});
}
}
app.get('/api/savedApp/', authentication, function(req, res) {
if (req.rsaConPortal.status !== 'registered') {
res.send({status: 'invalid'});
} else {
User.find({ "_id": req.rsaConPortal.id }, {
profile: 1, documents: 1 }, function(err, user) {
if (err) throw err;
res.send(user);
});
}
});
Is there a better way to authenticate my users? I am using Mozilla's Client-Sessions npm package
The logs on the server are logging "Passed1" and "Passed2". It is sending the client "Invalid" based off the status inside the get call.
Based on reading further about express and a few comments I have received on this question I have decided to re-think my approach and look for a better alternative which I am happy to say I have found in express.Router. I was able to create an authentication function to determine if the user is authorized and handle the business logic of whether to let the user pass or send them back to the login. Then I created a route for each page that I have that takes the business logic a step further based on the users status and either lets them pass or sends them back to login.
Thanks to everyone who looked into this and provided comments.
var router = express.Router();
app.use(router);
var authenticate = function(req, res, next) {
if (req.rsaConPortal !== undefined) {
if (req.rsaConPortal.email !== undefined) { // Check if session exists
// lookup the user in the DB by pulling their email from the session
User.findOne({ "user.email": req.rsaConPortal.email, "user.password": req.rsaConPortal.passport }, function (err, user) {
if (!user) {
// if the user isn't found in the DB, reset the session info and
// redirect the user to the login page
req.rsaConPortal.reset();
req.rsaConPortal.email = '';
req.rsaConPortal.passport = '';
req.rsaConPortal.id = '';
req.rsaConPortal.status = '';
res.redirect('../login');
} else {
req.rsaConPortal.email = user.user.email;
req.rsaConPortal.passport = user.user.password;
req.rsaConPortal.id = user._id + '';
req.rsaConPortal.status = user.user.status;
next();
}
});
} else {
res.redirect('../login');
}
} else {
res.redirect('../login');
}
};
router.get(['/','/create_warranty','/help','/marketing_assets','my_documents','profile'], authenticate, function(req, res, next) {
if (req.rsaConPortal.status !== 'approved') {
res.redirect('../login');
} else {
next();
}
});
I'm making a simple webapp with facebook login.
If the facebook login button on my page is clicked,
FB.api(
'/me',
'GET',
{"fields":"id,name,birthday,gender"},
function(response) {
$.post('fb_login', response, "json");
}
);
is called, and a router handles '/fb_login' request; in the router the server checks the id of json object is already in its DB. If not, res.render('signup', ...) should be called.
However it didn't work. I already checked that res.render() was called, but the page 'signup.jade' didn't show up.
Here is my source code of router.
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: '1012'
});
/* GET home page. */
router.post('/', function(req, res, next) {
var userid = req.body.id;
if (userid) {
pool.getConnection(function(err, connection) {
if (err) {
console.error('DB Connection error!!');
return;
}
console.log('DB Connection Success!!');
connection.query('use vasket');
connection.query('select count(*) result from user where userID=?',
[userid], function(err, result, field) {
var isAlreadyUser = result[0].result;
console.log(isAlreadyUser);
if (isAlreadyUser == 1) {
req.session.userid = userid;
res.redirect('/');
res.end();
console.log('DB FB Login Success!!');
connection.release();
}
else {
connection.release();
console.log('FIRST TIME!');
//This method was called, but the page rendered didn't
res.render('signup', {id: req.body.id, name: req.body.name, birthday: req.body.birthday, gender: req.body.gender});
}
});
});
} else {
res.redirect('/');
res.end();
}
How can I fix it?
To help debugging maybe you can modify your code like that :
// ... your code before
else {
connection.release();
console.log('FIRST TIME!');
console.log(req.body);
//This method was called, but the page rendered didn't
res.render(
'signup',
{
id : req.body.id,
name : req.body.name,
birthday: req.body.birthday,
gender : req.body.gender
} ,
function(err, html){
if(err) console.log(err);
console.log(html);
//res.send(html);
// trying same but forcing status
res.status(200).send(html);
}
);
}
});
});
} else {
res.redirect('/');
res.end();
}
This is an older question, but it's still in need of a solid answer. I had the exact same problem, but I think I've figured it out.
If the server's returning the proper response, that's not where your problem lies. jQuery (in the browser) will render the response, but you have to tell it to do so.
Here's what I had that was responding properly but not rendering:
$("#getsome").click(function() {
$.get("/task/create");
});
And here's how I got it to render:
$("#getsome").click(function() {
$.get("/task/create", function( data ) {
document.write(data);
});
});
Note that you may not need to replace the entire DOM like I'm doing.
References:
Replacing the entire
DOM
jQuery.get
I'm trying to generate a page with the post connected to an id, I've got the id in to the node function witch I can see in the console but i don't know how i can render a new view with this posts content?
thankful for all ideas!
i think something is wrong with the search do to the fact that I don't get the item value in the console
in my node js file
router.param('id', function(req,res, next, id){
console.log(req.params.id)
db.collection('insights').find({_id:req.params.id}).toArray(function (err, items) {
res.json(items);
console.log(items)
});
res.send(items);
});
router.get('/share/:id', function(req, res) {
res.render('contact');
});
The param() callback is generally not for directly responding to requests (although maybe in case of error). It's to be used for loading data from databases, etc.
Here's what you might do:
router.param('id', function(req, res, next, id) {
db.collection('insights')
.find({_id: id})
.toArray(function(err, items) {
if (err) {
console.error(err);
return res.send(404);
}
req._items = items;
next();
});
});
router.get('/share/:id', function(req, res) {
res.render('contact', { items: req._items });
});
In the below code i'm trying to fetch the user details from DB and save it to session. But unfortunately it doesn't work as i've expected, the data is not written into the session variable. I guess it's because of pass by value? Any workaround
exports.check = function(req,res,next){
..
..
getUserFromDB(req);
}
function getUserFromDB(req){
..
db.findOne(query,function(doc){
req.session.user = doc;
})
}
I think you are missing the callback call.
Are you using express and mongodb? We should post full working examples :)
exports.check = function (req, res, next) {
getUserFromDB(req, next);
};
function getUserFromDB(req, callback) {
db.findOne({ _id: req.qs.id }, function (err, doc) {
req.session.user = doc;
callback(err);
});
}
Also check for err, and also for null doc (not found).