API Calls with Axios fail on React

Issue

On handleSubmit i am trying to log in using an API hosted on Heroku and made based on ExpressJS. It is working fine when i am using Postman to reach the API on the login endpoint. But when using axios on react it fails.

Heroku login endpoint : https://nodejs-mongodb-authapp.herokuapp.com/login

Code :

import React, { useState } from "react";
import './Login.css' ;
import {FaMountain} from 'react-icons/fa';
import { Form, Button } from "react-bootstrap";
import axios from "axios";

import Cookies from "universal-cookie";



const cookies = new Cookies();
export const Login = () => {

    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");
    const [login, setLogin] = useState(false);
   const [state , setState] = useState(false);
   const axios = require("axios");
   
   const handleSubmit = (event) =>{
    
    const data = JSON.stringify({
        email: "[email protected]",
        password: "zzz",
      });
      const config = {
        method: "post",
        url: "https://nodejs-mongodb-authapp.herokuapp.com/login",
        headers: {
          "Content-Type": "application/json",
        },
        data: data,
      };
      
      axios(config)
      .then((result) => {
        alert("in thenn");
    //     setLogin(true);
    //     cookies.set("TOKEN", result.data.token, {
    //         path: "/",
    //       });
    //    navigate('/auth');
        
        
      })
      .catch((error) => {
        error = new Error();
       
      }); 


   }

    return(
       
        <div className="p1">
            <div className="log">
                <form className="formFields" >
                    <div className="lfa">
                        <FaMountain />
                    </div>
                    <p>LOG IN</p>
                    
                     <Form onSubmit={(e)=>handleSubmit(e)} className="form_">
                        {/* email */}
                        <Form.Group controlId="formBasicEmail">
                        
                        <Form.Control
                            type="email"
                            name="email"
                            value={email}
                            onChange={(e) => setEmail(e.target.value)}
                            placeholder="Enter email"
                        />
                        </Form.Group>

                        {/* password */}
                        <Form.Group controlId="formBasicPassword">
                        
                        <Form.Control
                            type="password"
                            name="password"
                            value={password}
                            onChange={(e) => setPassword(e.target.value)}
                            placeholder="Password"
                        />
                        </Form.Group>

                        {/* submit button */}
                        <Button
                        variant="primary"
                        type="submit"
                        onClick={(e) => handleSubmit(e)}
                        >
                        Login
                        </Button>
                    </Form>
                </form>
            </div>
            {/* {login ? (
          <p className="text-success">You Are Logged in Successfully</p>
        ) : (
          <p className="text-danger">You Are Not Logged in</p>
        )} */}
        </div>
        
    )
}

The API is public for the moment you can try login with those credentials on PostMan :

enter image description here

Solution

Well, I managed to test it and it does respond. The request should be done like this:


import React, { useState } from "react";
import { FaMountain } from "react-icons/fa";
import { Form, Button } from "react-bootstrap";
import Cookies from "universal-cookie";

const cookies = new Cookies();
export const Login = () => {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [login, setLogin] = useState(false);
  const axios = require("axios");

  const handleSubmit = (event) => {
    event.preventDefault();
    const data = JSON.stringify({
      email: "[email protected]",
      password: "zzz"
    });
    const config = {
      method: "post",
      url: "https://nodejs-mongodb-authapp.herokuapp.com/login",
      headers: {
        "Content-Type": "application/json"
      },
      data: data
    };

    axios(config)
      .then((result) => {
        alert("in thenn");
        console.log(result);
        setLogin(true);
        cookies.set("TOKEN", result.data.token, {
          path: "/"
        });
      })
      .catch((error) => {
        error = new Error();
      });
  };

  return (
    <div className="p1">
      <div className="log">
        <div className="lfa">
          <FaMountain />
        </div>
        <p>LOG IN (Login State {login.toString()})</p>
        <p>Token: {cookies.get('TOKEN')}</p>

        <Form onSubmit={(e) => handleSubmit(e)} className="form_">
          {/* email */}
          <Form.Group controlId="formBasicEmail">
            <Form.Control
              type="email"
              name="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="Enter email"
            />
          </Form.Group>

          {/* password */}
          <Form.Group controlId="formBasicPassword">
            <Form.Control
              type="password"
              name="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="Password"
            />
          </Form.Group>

          {/* submit button */}
          <Button
            variant="primary"
            type="submit"
            onClick={(e) => handleSubmit(e)}
          >
            Login
          </Button>
        </Form>
      </div>
      {/* {login ? (
          <p className="text-success">You Are Logged in Successfully</p>
        ) : (
          <p className="text-danger">You Are Not Logged in</p>
        )} */}
    </div>
  );
};

Since you are sending a JSON with the access information through the body, you have to take the JSON structure and then chain it to send it through post, and you have to add the ContentType: application/json header.

UP: When forms are used and you use an input type submit, every time the login button is clicked, the component is updated, to avoid this add the following inside the function event.preventDefault();

Test it here

Answered By – KrLiTs

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published