Home > Mobile >  API Calls with Axios fail on React
API Calls with Axios fail on React

Time:08-07

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 : enter image description here

CodePudding user response:

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

  • Related