Search code examples
javascriptreactjsaxiosfetch

Error on console POST http://localhost:3000/login/signin 404 (Not Found) on Login page


I'm trying to do a login page using axios but got an error on the console saying : POST http://localhost:3000/login/signin 404 (Not Found) , I don't understand what I'm doing wrong. My route works perfectly fine on postman, but not in the front end. I attached my loginpage, route page and app.js. Can someone help?

import React from 'react';
import './LoginPage.css';
import axios from 'axios';

class LoginPage extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            email: "[email protected]",
            password: "test",
        }
    }

    handleChange = (e) => {
        this.setState({
            [e.target.name]: e.target.value,
        });
    };


    login = () => {
        const {email, password} = this.state;

        axios("/login/signin", {
            method: "POST",
            data: {
                email,
                password,
            },
                
            })
            .then((response) => {
                console.log(response);

            })
            .catch((error) => {
                console.log(error);
       
            });
};

    render() {
    return (
<div>
        <div className="text-center">
   
   <input className="login-input mb-4 mt-4" 
           placeholder="Email"
           value={this.state.email}
           onChange={this.handleChange}
           name="email"
           type="text"
   /><br></br>
     




   <input className="login-input" 
          placeholder="Password"
          value={this.state.password}
          onChange={this.handleChange}
          name="password"
          type="password"
          /><br></br>
          

          <div className="login-button-container">
            <button className="mt-4 button-input" onClick={this.login}>Sign in</button>
           
           
            </div>
            </div>
           
         

        </div>
    )
    }
}

export default LoginPage;

var express = require('express');
var router = express.Router();
var jwt = require('jsonwebtoken');

var db = require("../model/helper");
require("dotenv").config();

const supersecret = process.env.SUPER_SECRET;

router.post("/signin", function(req, res, next) {
  //login logic 
  const {email, password} = req.body;
  db(`SELECT * FROM login WHERE email = "${email}" AND password= "${password}";`)
  .then((results) => {
    if(results.data.length){
      //yes, there is a user
      //I need to generate a new token 
      var token = jwt.sign({ loginId: results.data[0].id}, supersecret);
      //send the token to the user
      res.send({message: "User OK, here is your token!", token})
    }
    else{
      res.status(400).send({message: "User not found!"})
    }
  });
});

router.get("/profile", function(req, res, next) {
  //send private token to user
  const token = req.headers["x-access-token"]
  if(!token) {
    res.status(401).send({message: "Please log in!"})
  }
  else {
    jwt.verify(token, supersecret, function (err, decoded){
      if(err) res.status(401).send({message: err.message});
      else {
        //everything is awesome
        const {loginId} = decoded;
        res.send({message: `Here is the private data for user ${loginId}!`})
      }
    })
  }
})

module.exports = router;

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var loginRouter = require('./routes/login');

var app = express();



app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/login', loginRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.send('error');
});

module.exports = app;


Solution

  • Because you have a nested route, you want to capture all other routes within /login route.

    You can do that with an asterisk (*).

    Do this instead:

    app.use('/login/*', loginRouter);
    

    Following updates in the comment section

    Since your backend is running on port 5000 then you should be making an Axios API call like this

    axios("https://localhost:5000/login/signin", {})
    

    OR add a proxy to your package.json file

    "proxy": "localhost:5000"