Usuhuu
Usuhuu

Reputation: 21

Failed to load resource: the server responded with a status of 404 () nodes, react, mysql

my English is not so good. using a node js and react js with mysql. signup page work properly but login page getting a error "Failed to load resource: the server responded with a status of 404 ()"

  1. server.js(node.js)

    const express = require("express");
    const app = express();
    const session = require('express-session');
    const bodyParser = require('body-parser');
    const cors = require("cors");
    app.use(express.json());
    app.use(cors());
    const { sequelize } = require('./db'); // Import Sequelize instance
    
    sequelize.authenticate()
    .then(() => {
      console.log('Database connection has been established successfully.');
    })
    .catch((error) => {
      console.error('Unable to connect to the database:', error);
    });
    
    app.use(express.static('public'));
    app.use(bodyParser.urlencoded({ extended: true }));
    app.use(session({
      secret: 'secret-key',
      resave: false,
      saveUninitialized: true,
      cookie: { maxAge: 3600000 }
    }));
    
    
    const signup = require("./routes/signup");
    app.use("/auth",signup);
    
    const login = require("./routes/login");
    app.use("/auth", login);
    
    
    const dashboard = require("./routes/dashboard");
    app.use("/auth",dashboard)
    
    
    const PORT = process.env.PORT || 3001;
    app.listen(PORT, () => {
      console.log(`Server is running on port ${PORT}`);
    });
    
  2. db.js(node.js)

    const { Sequelize, DataTypes } = require('sequelize');
    const config = require('./config/config.json');
    const userTable = require('./models/userTable');
    
    const dbConfig = config.development;
    
    const sequelize = new Sequelize(dbConfig.database, dbConfig.username, dbConfig.password, {
      host: dbConfig.host,
      dialect: dbConfig.dialect
    });
    const User = userTable(sequelize, DataTypes);
    
    
    module.exports = {
      sequelize,
      User,
    };
    
  3. login.js (node.js)

    const express = require('express');
    const router = express.Router();
    const path = require('path');
    const {User} = require('../db');
    const bcrypt = require('bcrypt')
    
    
    const { naverClientId, appleClientId, kakaoClientId } = require('../config/clientID.json');
    const { Result } = require('express-validator');
    
    
    router.get('/naver-login', (req, res) => {
      // Redirect to Naver for login
      res.redirect(`https://nid.naver.com/oauth2.0/authorize?response_type=code&client_id=${naverClientId}&redirect_uri=YOUR_REDIRECT_URI&state=YOUR_STATE`);
    });
    
    router.get('/apple-login', (req, res) => {
      // Redirect to Apple for login
      res.redirect(`https://appleid.apple.com/auth/authorize?client_id=${appleClientId}&redirect_uri=YOUR_REDIRECT_URI&response_type=code&scope=name%20email`);
    });
    
    router.get('/kakao-login', (req, res) => {
      // Redirect to Kakao Talk for login
      res.redirect(`https://kauth.kakao.com/oauth/authorize?client_id=${kakaoClientId}&redirect_uri=YOUR_REDIRECT_URI&response_type=code`);
    });
    
    router.post("/login", async (req,res) => {
      const {email, password} = req.body;
      try {
        const user = User.findOne({where: {email}});
        if(!user) {
          return res.status(401).json ({ message: "invalid email or password"});
        }
    
        const isPasswordValid = await bcrypt.compare(password, user.password);
    
        if(isPasswordValid) {
          req.session.user = user; 
          return (
            // res.status(200).json({ message: 'Login successful', user })
            res.redirect("/auth/dashboard")
          )
        } else {
          return (
            res.status(401).json({ message: 'Invalid email or password' })
          )
        }
      } catch (error) {
        console.error('Error during login:', error);
        res.status(500).send('An error occurred');
      }
      });
    
    
    module.exports = router;
    
    
    
  4. login.jsx(react.js)

    import React, { useState } from 'react';
    import { Link } from 'react-router-dom';
    import axios from 'axios'; 
    import "../CSS/login.css";
    
    function LoginPage() {
      const [email, setEmail] = useState('');
      const [password,setPassword] = useState('');
    
    
      const handleSubmit = async (e) => {
        e.preventDefault();
    
        try {
          const response = await axios('http://localhost:3001/auth/login', { email,password });
          if (response.status === 200){
            const data = response.data;
    
            console.log(data);
            window.location.href = 'auth/dashboard';
    
          }else {
            console.error("login failed");
          }
        }
        catch (error) {
          console.error('error: ', error);
        }
      }
    
    
      return (
        <div>
          <header>
            <div className="login-form">
              <form action="/auth/login" method="POST">
                {/* Username Input */}
                <label htmlFor="email">이메일</label>
                <input
                  type="email"
                  id="email"
                  name="email"
                  required
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                />
                {/* Password Input */}
                <label htmlFor="password">비밀번호</label>
                <input
                  type="password"
                  id="password"
                  name="password"
                  required
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                />
    
                {/* Email Login Button */}
                <button type="submit">이메일 로그인</button>
    
                {/* Forget Password and Sign-Up Links */}
                <div className="forgetPassword">
                  <Link to="/auth/forgetpassword" id="forgot-password-link">비밀번호 찾기?</Link>
                  <Link to="/auth/signup" id="sign-up-link">회원가입</Link>
                </div>
    
                {/* Social Media Login Buttons */}
                <div className="authorityLogin">
                  <div className="naverLogin">
                    <button type="button" id="naver-login">
                      <Link to="/naver-login"><img src="/Photo/naverLogin.png" alt="naver login" /></Link>
    
                    </button>
                  </div>
    
                  <div className="appleLogin">
                    <button type="button" id="apple-login">
                      <Link to="/apple-login"><i className="fab fa-apple"></i></Link>Apple로 로그인
                    </button>
                  </div>
    
                  <div className="kakaoLogin">
                    <button type="button" id="kakao-login">
                      <Link to="/kakao-login"><img src="/Photo/kakaoLogin.png" alt="kakao login" /></Link>
                    </button>
                  </div>
                </div>
              </form>
            </div>
          </header>
        </div>
      );
    }
    
    export default LoginPage;
    
    

my signup page work properly but my login doesn't work

my login.jsx(login.js) keep getting a (Failed to load resource: the server responded with a status of 404 ())

Upvotes: 2

Views: 129

Answers (1)

  1. Replace the axios part in login.jsx with this one
const response = await axios.post('http://localhost:3001/auth/login', { email, password });

If you are using axios() instead of axios.post(), you should do it like this

const config = {
  method: 'post',
  url: 'http://localhost:3001/auth/login',
  data: { email,password },
};
axios(config);

Upvotes: 0

Related Questions