0

I am trying to redirect the user with a post request from the home page after checking if their sessions exist.

This is my home controller file:-

const express = require('express');

const router = express.Router();

router.get('/', (req, res, next) => {
    if (req.session["Data"] != undefined) {
        res.redirect(307, '/Try');
    }
    else {res.render('home', {pageTitle: "Home"});}
});

module.exports = router;

But it is giving me error- Cannot GET /Try

This is what I'm using in my route file- router.post('/Try', try_controller.Try);

I am using res.redirect(307, '/Try') in another controller file of the same project and it's working. I can't figure out why it's not working here.

  • 1
    Where is the `/Try` route registered? – NullDev Nov 24 '21 at 15:27
  • @NullDev it's registered in my route file as post. –  Nov 24 '21 at 15:49
  • 1
    307 preserves the original request method. For your `/` route it is `GET` so you'll need a `router.get("/Try", ...)` handler – Phil Nov 25 '21 at 03:11
  • Does this answer your question? [How to redirect to post request in express](https://stackoverflow.com/questions/45174857/how-to-redirect-to-post-request-in-express) – Phil Nov 25 '21 at 03:13
  • @Phil I don't want the user to access the `/Try` page without having sessions stored. So I don't think I can use `router.get()`. –  Nov 25 '21 at 04:12
  • I'm facing the same issue, is there any solution you get ? – mohit jain Jul 20 '22 at 11:28

2 Answers2

0

I don't think you can redirect a GET as a POST. If you own the /Try route, one option is to add a GET handler for that, then redirect will work.

Otherwise, in your GET route handler for \ you can create a new POST and return the results of that.

const request = require('request')
router.get('/', (req, res, next) => {
    if (req.session["Data"] != undefined) {
        //res.redirect(307, '/Try');
        request.post('/Try', {}, function(err, response, body) {
           if (err) return next(err)
           return res.status(response.statusCode).send(body);
        })
    }
    else {res.render('home', {pageTitle: "Home"});}
});

The example above an https://github.com/request/request though there are more modern ways of sending POST from express.

This isn't technically "redirecting", so you won't return 307 or 302.

prototype
  • 7,249
  • 15
  • 60
  • 94
0

I tried different things but in the end, I added an empty form in my home.pug file and submitted it using js.

JS code -

script.
    let ssn = !{JSON.stringify(session)};
    data = "Data"
        
    if (ssn[data] != undefined) {document.getElementById('form-id').submit();}