Patty
Patty

Reputation: 83

Node JS redirecting

I am very new to node JS. I would like to simply redirect buttons to another page, but every time I try to redirect i am greeted with a cannot GET /(the page that I am trying to redirect to). the current syntax I am trying to implement to redirect looks like this:

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/brand', ensureAuthenticated, function(req, res) {
  res.render('index');
});

I don't know if I just put it in the wrong place or what, but I need a help on this one. Thank you

Upvotes: 0

Views: 685

Answers (6)

Rahul Dey
Rahul Dey

Reputation: 107

You have to use Some view engine for serving on the page to another.

Lets Example I have a Login jade(pug) file.

doctype html
html
  head
    script(src='https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js')
  body
    p
      | Username 
      input(type='text', name='username' ,id='name')
    p
      | Password 
      input(type='password', name='password' ,id='password')
    p
      input(type='Submit', value='Login' onclick="login()")
      |  
      a(href='http://localhost:8000/register') New Register
    p
      #{error}  
    script.
      function login(){
      $.post("http://localhost:8000/login",
      {
        username:document.getElementById("name").value,
        password:document.getElementById("password").value,
      },
      function(data, status){
         if(data.success===true){
            window.location="http://localhost:8000/welcome"
         }
         else{
         window.location="http://localhost:8000/"
         }

      });
      }

So This is "login.pug" file.When "/login" api will be called from this file, it will hit my server api (/login api)

app.post('/login', function(req, res, next) {

    checkExistanceOfuser(req.body.username, req.body.password, function(err, flag, data) {
        console.log(err);
        if (err) {
            res.send({
                err: 'SOME_DATABASE_ERROR'
            })
        } else {
            if (flag) {

                req.session.user = data;

                res.send({
                    success: true,
                    message: 'Login Success'
                })


            } else {
                res.send({
                    success: false,
                    message: 'Invalid Credentials'
                });

            }
        }
    })
});  

Depending on post response `"window.location" I change the view. For Example, after successful login response, I send it on

http://localhost:8000/welcome

Now, this calls a get request on /welcome API. I write this file in server

app.get('/welcome', function(req, res, next) {
    if (req.session && req.session.user) {
        res.render('welcome', { name: req.session.user.name })
    } else {
        res.render('login', { error: 'Invalid Session' });
    }
});

In this way, you can change the view.

Maybe it will helpfull.

Upvotes: 0

Jayant Jaiswal
Jayant Jaiswal

Reputation: 181

You need to require your routes file for which you've shown the code in app.js in the following way:

var routes = require('./routes/routes');

So that to the main app.js where you've defined your app and set the views and engine, the routes are available.

Upvotes: 0

md asif rahman
md asif rahman

Reputation: 389

to redirect to any page in express js you can simply use redirect method in your controller.

res.redirect('controller/method');

Upvotes: 0

user2672124
user2672124

Reputation:

You need to mention the path to the file you want to send on getting a request to that route.

One way to do it:

var path = require('path');
router.get('/brand', function(req, res) {
       res.sendFile(path.join(__dirname,'/path/to/index.html');
}

Another way to serve static files :

app.use('/stat', express.static(__dirname + '/public'));
// allows you to access files through : localhost:port/stat/somefile

On your frontend, for buttons that redirect: (jquery)

$('#yourBtnId').click(function() {
   window.location.href = 'localhost:8080/brand';
});

Upvotes: 0

Nitzo
Nitzo

Reputation: 79

Looks like you are missing the routes you are redirecting to.

You need to define every route you are going to use. Each route that is not defined will return a "cannot GET /xxx" with a 404 status code.

You define another route by simply adding:

router.get('/route_path', function(req, res) {
   // Do something
});

Upvotes: 0

Medet Tleukabiluly
Medet Tleukabiluly

Reputation: 11950

This simplest example with redirection should work

var express = require('express');
var app = express();

app.get('/', function(req, res) {
   res.sendFile(__dirname + '/index.html'); // create your index.html file
});
app.get('/brand', function(req, res) {
   res.redirect('/');
});

app.listen(3000, function() {
  console.log('Express listening at 3000'); 
});

Upvotes: 1

Related Questions