reactjs 从路由文件夹请求时Axios 404

7dl7o3gd  于 2023-01-12  发布在  React
关注(0)|答案(3)|浏览(166)

我在Express和Node.js中有一个server.js文件,它包含了我的大部分后端代码,在我的数据库配置文件之外。
该文件相当长,为了提高可维护性,我希望通过将各种组件拆分为可以导入的文件来使其模块化。
我尝试将数据库端点作为起点移动到它自己的文件auth.js中,该文件位于routes文件夹中。

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;

然后,通过要求auth.js文件并将其与路由“/signin”一起使用,在主server.js文件中使用该文件:

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

最后,我在React前端应用程序上向/signin路由发出请求。

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')
        };
    });
  };

为了添加一些上下文,这是一个登录表单,并根据在数据库中找到的行验证输入到表单中的登录数据。直到我将端点移动到一个单独的文件中,我现在才收到预期的效果:AxiosError {message: 'Request failed with status code 404', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}在我的前端。我想知道如何解决这个问题。

pbossiut

pbossiut1#

问题是app.use('/signin', authRoutes)使端点成为“/signin/signin”而不仅仅是您试图请求的“/signin”。最简单的解决方案是将您在www.example.com函数中传递的链接更改axios.post为“http://localhost:8080/signin/signin”。

cyej8jka

cyej8jka3#

您需要侦听端口8080

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

相关问题