Home > Software design >  Axios 404 when requesting from routes folder
Axios 404 when requesting from routes folder

Time:01-12

I have a server.js file in Express and Node.js that contains the majority of my back-end code, outside of my database config file.

The file is quite long and to improve maintainability, I would like to make it modular by splitting various components into their own files that can be imported.

I have attempted to move a database endpoint as a starting point into its own file called auth.js, located in the routes folder. The file is set up as follows:

const express = require('express');
const router = express.Router();
const db = require('../config/db');

const crypto = require("crypto"); // set up crypto middleware for hashing password and checking password hashes

const salt = crypto.randomBytes(256).toString("hex"); // create a hash salt/pepper
const iterations = 1000; // number of iterations to jumble the hash
const hashSize = 64; //set up char length of hash
const hashAlgorithm = "sha256"; // which hashing algorithm will be used

//This function returns a hash of the password, combined with the pepper and the salt.
function PasswordHash(password, salt) {
    //PEPPER MUST BE MOVED TO ENV FILE WHEN READY
    const pepper = "ec3fd71d14f7cab570fc94df34e60e4d8c80cdff4d1dde66c74b10ae576b88239315295adabaced63b05104bbf8d2f2f92a24aeebe8444861ba1b7efc73dafdeda6fe2bf6e7288f959832d5db953a7eab0b37ef8ad126f94616b0c1e7b3b0ce7418dff91afaa78401dacce6aee72649840e26a01d75bfac69acf8d0dd50aaddebb9397150bb0f88795cde94ea3d03fec2992fc3b5c3c7bbd8de3f8f7d693cdcca879d9aefd6e02d4457217928091a731c08f83f9927f9b19ca34ab589dd02ecc40e336e067a1f2e072ec2b3a93617ded73028ed5bc5d55f011ba5a53099312f06d649fa06fdbf49e81c8f9a81f113f95cd416d230c2cb6056189c77f889dc83d";
    
    return crypto.pbkdf2Sync (
        password,
        salt   pepper,
        iterations,
        hashSize,
        hashAlgorithm
    ).toString("hex");
};

// login route
router.post('/signin', (req, res) => {
    const { email, password } = req.body;

    // Check all emails against input
    db.query(selectEmail, [email], (err, rows) => { 
        if (err) throw err;
        // If email exists
        if (rows.length > 0) {
            // If password with salt and compares to database 
            if (PasswordHash(password, rows[0].salt) == rows[0].password) { 
                // Create session
                req.session.firstName = rows[0].first_name;
                req.session.lastName = rows[0].last_name;
                req.session.username = rows[0].user_name;
                req.session.ProfilePicture = rows[0].profile_picture;

                console.log('Session created:', req.session); // Print session
                res.send('Login successful');
            }

            // If password is incorrect
            else {
                res.send('Email or password are incorrect');
            }
        }

        // If email does not exist
        else {
            res.send('Email or password are incorrect');
        };
    });
});

module.exports = router;

This is then used in the main server.js file by requiring the auth.js file and using it with the route '/signin':

const authRoutes = require('./routes/auth');
app.use('/signin', authRoutes);

Finally, I make a request on my React front-end application to the /signin route.

  const validateRow = () => {
    // Validate login
    axios.post('http://localhost:8080/signin', {
      email: emailInput,
      password: passwordInput
    })
    .then((res) => {
        setMessage(res.data);

        //If validation passed
        if (res.data === 'Login successful') {
          navigate('/directory')
        };
    });
  };

To add some context this is for a login form and validates login data inputted into the form against rows found in the database. This worked as intended until I moved the endpoint into a separate file I now receive: AxiosError {message: 'Request failed with status code 404', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …} on my front end. I would like to know how to resolve this issue.

CodePudding user response:

The issue is that app.use('/signin', authRoutes) makes an endpoint be "/signin/signin" not just "/signin" which you are trying to request. The simplest solution would be to change link you pass in axios.post function to "http://localhost:8080/signin/signin".

CodePudding user response:

Try using relative path as suggested in this (possible duplicate):

I don't understand why my axios post request isn't working - 404 not found

CodePudding user response:

You need to listen to the port 8080

const app = express()
const port = 8080
app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})
  • Related