React 404 Axios Cannot POST

New to Axios and Node as a backend- have inherited some code in React for a login page and am trying to figure out why I can’t make a POST to the backend.

This is my .env file:

REACT_APP_BACKEND_URL=http://localhost:3000/admin

And there is a file called API.js

import axios from "axios";

// Set config defaults when creating the instance

export const CompanyAPI = () => {
  let api = axios.create({
    baseURL: process.env.REACT_APP_BACKEND_URL,

    timeout: 10000,
    headers: {
      "Content-Type": "application/json",
    },
  });

  return api;
};

And then there is a LoginPage.js:

export const LoginPage = () => {
  const API = CompanyAPI();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const getAuth = (e) => {
    e.preventDefault();
    API.post("/auth/login", {
      email: email,
      password: password,
    })
      .then(async (response) => {
        if (response.status === 200) {
          await localStorage.setItem("jwt_key_admin", response.data.token);

          setTokenKey(response.data.token);
          setIsAuth(true);
          navigate("/");
        }
      })
      .catch((error) =>
        alert(
          "Login Failed"
        )
      );
  };

enter image description here

enter image description here

My question is, is there an example on how I could use express to handle the /auth/login endpoint and complement the existing API.js file?

2 thoughts on “React 404 Axios Cannot POST”

  1. Basically what I see from this code is:

    • An axios instance was created and the baseURL was set to being http://localhost:3000/admin

    • From first glance I can tell that all Api calls that you make a resulting to 404 reason being React locally will always run on port 3000 unless that port is in use.

    • So now your axios baseURL being to set to port 3000 definitely axios should return a 404 because you surely do not have the endpoint that you are trying to hit

    Solution:

    • Here you are to change the baseURL’s port number to the port where Nodejs server is listening on

    • Then once that is said and done then make sure that even the endpoints that you are trying to hit do exist then your axios calls should work now

    Advise:

    • If the Axios instance created is confusing drop it for a bit and import raw axios not the instance then use axios in it’s basic form then once you have that working you surely will have established the correct port number and everything then you can edit the axios instance created with baseURL you have established.
    Reply

Leave a Comment