React-gatsby登录身份验证失败

时间:2020-09-19 06:13:26

标签: reactjs authentication gatsby

我正在为我的应用程序使用Gatsby。我从Mock api创建了一个api。我的api看起来像this。我已经发出了一个登录后请求,当用户输入他/她的电子邮件和密码时,如果不匹配,则将警告“登录失败”,或者如果登录成功,它将警告(“成功登录”)并导航到成功的页面。但是我输入的电子邮件和密码总是表明我成功登录,这是错误的逻辑。该电子邮件应类似于我api的电子邮件:alak@gmail.com"和密码:test123。我认为我的逻辑正确,但我仍然犯错。我在Codesandbox中共享我的代码。 PS: Codesandbox is based on react. but logic is same as my below code

这是我的代码:

import React, { ReactElement, useState } from 'react';
import { PageProps, navigate } from 'gatsby';
import styled from 'styled-components';
import MainTemplate from '../templates/index';
import { TextInput } from '../components/textInput';
import { Button } from '../components/buttons';
import { API_URLS } from '../utilities';

interface Props extends PageProps {

}

export default function SignIn({ }: Props): ReactElement {
  const [state, setState] = useState({
    "email": ``,
    "password": ``,
    "loading": false

  });
  const { loading } = state;
  const signInValue = (e) => {
    setState({
      ...state,
      [e.target.id]: e.target.value
    });
  };
  const onSubmit = async (e) => {
    e.preventDefault();
    console.log(state);
    setState({
      "loading": true,
      ...state
    });
    const response = await fetch(`https://run.mocky.io/v3/beec46b8-8536-4cb1-9304-48e96d341461`, {
      "method": `POST`,
      "headers": {
        "Accept": `application/json`,
        'Content-Type': `application/json`
      },
      "body": { state }
    });
    if (response.ok) {
      alert(`you have suceefully login`);
      navigate(`/success`, { "state": { email } });
    } else {
      alert(`login failed`);
    }
  };
  return (
    <MainTemplate>
      <TextInput
        type="text"
        value={state.email}
        onChange={signInValue}
        id="email"
        required
      />
      <TextInput
        type="password"
        value={state.password}
        onChange={signInValue}
        id="password"
        required
      />
      <Button
        type="submit"
        name="action"
        onClick={onSubmit}
        disabled={loading}
      >  {loading ? `loading...` : `save`}
      </Button>

    </MainTemplate>
  );
}

1 个答案:

答案 0 :(得分:0)

根据fetch specification

从fetch()返回的Promise不会拒绝HTTP错误状态,即使响应是HTTP 404或500。它也会正常解析(ok状态设置为false),并且只会拒绝网络故障或是否有任何原因阻止请求完成。

因此您的api可能返回错误,但是response.ok可能仍然为true。您应该改为选中response.status !== 200

更新:根据您的沙箱,其工作原理如下所示enter image description here