How can i refresh the current page using node js and express - node.js

I want to refresh my page using respone and here is my code:
app.post("/delete",function(req,res){
res. <<-HERE I WANT TO REFRESH THE CURRENT PAGE USING "res."
})
If you think this question is stupid, please forgive me for that because iam a beginner :)

You can either redirect the browser to the page URL after the delete action:
app.get("/", function(req, res) {
res.render("page.ejs");
});
app.post("/delete", function(req, res) {
/* Carry out deletion */
res.redirect("/");
});
or you can include the code that generates the page in both the GET and POST routes:
app.get("/", function(req, res) {
res.render("page.ejs");
});
app.post("/delete", function(req, res) {
/* Carry out deletion */
res.render("page.ejs");
});
The important point is that, in both cases, the rendering of the page must take into account the prior deletion. Without you sharing more of your code, we cannot judge whether that works in your case.

Related

Changing sent HTML files using express?

I am trying to set up a basic login page using express, socket.io, and nodejs. I initially serve the client an index page using:
app.get('/', function (req, res) {
res.send(__dirname + '/index.html');
});
I have the logic for authentication set up. I need to know how to then route my user to the successful login page. I am having trouble understanding the way this middleware works, and any help would be appreciated.
Usually you need to check the req.user object, it will hold the current logged in user object, that is a good practice to fill this req.user if you are building your own auth layer, I'm not sure if you are doing that or not, but I would recommend using the very good passport npm package
So you can have something like:
app.get('/', function (req, res) {
if(req.user) { // user is logged in
res.send(__dirname + '/index.html');
}
else { // anonymous user
res.send(__dirname + '/login.html');
}
});

nodejs+express+passort local 404 error when trying to logout

I am trying to add logout feature using passport local strategy.
I followed the solutions discussed here, here and here
I added a
a(href='/logout') logout
link in my index.jade file.
In my app.js I added the following:
app.get('/logout', function (req, res) {
console.log("trying to logout....")
req.session.destroy()
req.logout()
res.redirect('/signin');
});
But when I click the logout href It goes to my 404 page. In the browser url I see that it is attempting to go to:
localhost:3030/logout
I event added an empty logout.jade view but it makes no difference.
What am i doing wrong?
Also - I do not see the console.log("trying to logout...") message in my terminal... so it looks like it never reached the correct method.
Found answer thanks to #renatoargh pointing out that order of routes matter.
Somewhat annoyed that the passport docs don't mention this!!
BEFORE:
app.use(route.notFound404);
app.get('/logout', function (req, res) {
console.log("trying to logout....")
req.session.destroy()
req.logout()
res.redirect('/signin');
});
SOLUTION:
app.get('/logout', function (req, res) {
console.log("trying to logout....")
req.session.destroy()
req.logout()
res.redirect('/signin');
});
app.use(route.notFound404);

can I create a route that could be use both for serving HTML and REST API?

Okay here's the scenario, to my knowledge there are three ways to create a web application
Traditional way: Render the HTML page from the server
Not sure: Create an API and let the user's browser to download the
Javascript application (Angular, React, Ember) to get a highly
interactive application
The future: Isomorphic web app, which render the HTML together with the client-side technologies (Angular, React, Ember) from the server.
I'm planning to use the third way, due to faster load page, but the problem right now is if I were about to create a mobile application.
My stack: Node.js + React
Let say if I'm planning to go mobile, do i need to duplicate the same route and logic ?
Current problem
app.get('/users', function(req, res) {
res.render('index', { message: "Hey Im Jack" });
});
app.get('/api/users', function(req, res) {
res.json({ message: "Hey Im Jack" })
});
Is there any way that I could use to for one route to serve both the HTML and REST?
You can ultimately only send either HTML or JSON (in case of REST).
The /api/xxx route syntax makes it clearer which path serves the JSON.
But you can depend on client's request header to check whether they requested JSON or HTML
app.get('/users', function(req, res) {
if (req.headers.accept && req.headers.accept.match(/json/))
res.json(data);
else
res.render('index', data);
});
Angular's $http usually requests json by default, not sure about others, but you can set the headers. Browsers normally request text/html, but I'm not sure.
Or if you're only concerned about not having to repeat the logic that fetches the data, you could put a middleware preceeding both:
// regex to match both routes
app.get(/.*users/, function(req, res) {
res.locals.data = { message: "Hey Im Jack" };
req.next();
});
app.get('/users', function(req, res) {
res.render('index', res.locals.data);
});
app.get('/api/users', function(req, res) {
res.json(res.locals.data)
});

In express how do I redirect a user to an external url?

I have a payment system using node.js and braintree, when the payment is successful I want to send the user to the back end. My back end is setup elsewhere.
I have tried
res.writeHead(301,
{Location: 'http://app.example.io'}
);
res.end();
So window.location is obviously not available. I cant think of any ways to redirect a user?
You can do
res.redirect('https://app.example.io');
Express docs: https://expressjs.com/en/api.html#res.redirect
The selected answer did not work for me. It was redirecting me to: locahost:8080/www.google.com - which is nonsense.
301 Moved Permanently needs to be included with res.status(301) as seen below.
app.get("/where", (req, res) => {
res.status(301).redirect("https://www.google.com")
})
You are in the same situation since your back-end is elsewhere.
app.get("/where", (req, res) => {
res.status(301).redirect("https://www.google.com")
})
You need to include the status (301)
I just have the same issue and got it work by adding "next". I use routers so maybe you have same issue as mine? Without next, i got error about no render engine...weird
var express = require('express');
var router = express.Router();
var debug = require('debug')('node_blog:server');
/* GET home page. */
router.get('/', function(req, res, next) {
debug("index debug");
res.render('index.html', { title: 'Express' });
});
router.post("/", function (req, res, next) {
//var pass = req.body("password");
//var loginx = req.body("login");
//res.render('index.html', { title: 'Express' });
res.redirect("/users")
next
});
module.exports = router;
None of these worked for me, so I tricked the receiving client with the following result:
res.status(200).send('<script>window.location.href="https://your external ref"</script>');
Some will say if noscript is on this does not work, but really which site does not use it.

accessing session variables in redirected file in node.js

I am building a crappy login system as a newbie. I have done this so far:
app.post("/verifyLogin",function(request,response){
var usr=request.body.username;
var pass=request.body.password;
userModel.find({$and:[{username:usr},{password:pass}]},function(err,user){
if(user.length==0)
{
response.redirect("/?msg=failed");
}
else
{
request.session.user=user;
response.redirect("/dashboard");
}
});
});
This works fine but after successful login i want to get the user details in the dashboard. I am clueless. Please shed some light.
EDIT
I have the following setup for dashboard in routes:
app.get("/dashboard",function(request,response){
response.sendfile('/lms/site/dashboard.html');
});
If you mean you want to pass the users' details to a template:
app.get('/dashboard', function(req, res) {
res.render('dashboard', {
user : req.session.user
});
});
This assumes a few things though:
you have a working templating setup;
you have a template called dashboard (with an extension matching your templating setup);
you're going to provide some sort of setup to make sure a user is logged in before they can open /dashboard.
EDIT: since you don't want to use templating, you could use AJAX to get the user details from the server into the client:
// server side
app.get('/userdata', function(req, res) {
// check if a user is logged in
...
// return the user details as JSON
res.send(req.session.user);
});
// client side (in 'dashboard.html', this assumes is will load jQuery)
$.getJSON('/userdata', function(user) {
// process user data, insert it into the DOM somewhere...
});
EDIT 2: to check if a user is logged in, you could create a middleware which would check for the existence of req.session.user and redirect to the login page if it's undefined:
var isLoggedIn = function(req, res, next) {
if (req.session && req.session.user)
next(); // user logged in, so pass
else
res.redirect('/'); // not logged in, redirect to login page
};
You would use the isLoggedIn middleware for all routes that require a user to be logged in:
app.get('/userdata', isLoggedIn, function(req, res) {
res.send(req.session.user);
});

Resources