首页 > 解决方案 > API登录反应未连接

问题描述

在此处输入图像描述我正在尝试登录/注册一个新用户,但是,它不会让我,我不知道如何修复它。我该怎么办?我试图找出如何做到这一点,但这对我来说有点复杂,我不知道。就像代码不想工作一样。

enter code here
import React, { useEffect, useState } from "react";
import LoginForm from "../LoginForm";
import Auth from "../../utils/Auth";
import { useLocation, useHistory } from "react-router";
//Uses the Auth methods to actually login with the LoginForm Component.

function Login() {
  let location = useLocation();
  let history = useHistory();
  const [redirectToReferrer, setRedirectToReferrer] = useState(false);

  useEffect(() => {
    const { from } = location.state || { from: { pathname: "/protected" } };
    if (redirectToReferrer) {
      history.push(from);
    }
  }, [redirectToReferrer, history, location.state]);

  /* We need to POST to the API the users info,
        This will get passed down as a prop to the LoginForm */
  const login = (data) => {
    console.log("Logging in " + JSON.stringify(data));
    //fetch('api/users/login', { is the error
    fetch("api/users/login", {
      method: "POST",
      body: JSON.stringify(data),
      credentials: "include",
      headers: {
        "Content-Type": "application/json",
      },
    })
      .then((response) => {
        if (response.status === 200) {
          //All good
          Auth.authenticate(() => {
            //Update the boolean and take off the cuffs
            setRedirectToReferrer(true);
            console.log(`Response in login ${JSON.stringify(response)}`);
          });
        }
      })
      .catch((err) => {
        // No beuno, kick them
        console.log("Error logging in.", err);
      });
  };

  return (
    <div>
      <LoginForm onLogin={login} />
    </div>
  );
}

export default Login;

标签: reactjs

解决方案


推荐阅读