Search code examples
javascriptnode.jsexpresshttprequest

Cant get Express to redirect to main page after user login


I'm trying to setup a user login section. The user_router is sending a JSON response just fine however I can't get Express to send a new html page back to the client. The first page that is offered is login.html which has the submission form for the login verification. The goal is to send back a 200 status message along with the actual app.html page upon login verification. The status message is working however the Express sendFile is not redirecting the browser to the app.html page. What am I doing wrong here?

The app.js file is loaded first. It has the following config:

const user_router = require( './router/user_router' );
const path = require( 'path' );
const public_directory = path.join( __dirname, '../public' );
const express = require( 'express' );
const app = express();
app.use(express.static( public_directory , {index: 'login.html'}));
app.use( user_router );
app.use( express.json() );

The user_router.js file where the validation and redirect should happen.

const auth = require( '../middlewear/auth' );
const express = require( 'express' );
const User = require( '../model/user_model' );
const router = new express.Router();
router.use( express.json() );

router.post( '/users/login' , async ( req , res ) => {
        
    try {       
        const user = await User.find_by_credentials( req.body.email , req.body.password );      
        const token = await user.create_token();
        const path = require( 'path' );     
        const app = path.join( __dirname, '../../public/app.html' );        
        res.sendFile( app );
        res.send( { user , token } );
    }
    catch( err ){
        res.status( 400 ).send();
    }
});

Solution

  • If you want to issue a redirect response the you need to use the redirect method.

    The sendFile method sends a file … for the URL the client asked for. It very much does not redirect them.

    The send method also sends a response that isn't a redirect.


    What's more, a request can only have one response to it (well, unless you make use of the new features in HTTP/2)

    redirect, sendFile, or send: Pick one (which should be redirect if you want to redirect!)