gpt4 book ai didi

reactjs - React Formik onSubmit RestAPI 调用两次,一次单击提交按钮

转载 作者:行者123 更新时间:2023-12-04 12:42:28 25 4
gpt4 key购买 nike

我在 React 中使用 Formik 和 Yup,当我单击提交按钮并触发 onSubmit 事件时,在事件内部,fetch 函数调用了两次,

import React, { Component } from 'react';
import Button from '@material-ui/core/Button';
import Container from '@material-ui/core/Container';
import { TextField } from 'formik-material-ui';
import { Formik, Field, Form } from 'formik';
import * as Yup from 'yup';
class LoginForm extends Component {
constructor(props) {
super(props);
this.state = {classes: this.props.classes, isLoading: false }
}
render() {
return (
<Formik
initialValues={initialFormValues}
validationSchema={validationFrom}
onSubmit={(values, actions) => {
this.setState({ isLoading: true });
console.log(values);
actions.setSubmitting(false);
console.log('SUCCESS!! :-)\n\n' + JSON.stringify(values, null, 2));

fetch('http://xx.xx.xx.xx.compute-1.amazonaws.com:9000/api/v1/userAuth', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(values)
})
.then(Response => {
console.log(Response);
this.setState({ isLoading: false });
})
}
}
render={({ submitForm, isSubmitting, isValid }) => (
<Form>
<Container component="main" maxWidth="xs" >
<div className={this.state.classes.paper}>
<Field
variant="outlined" margin="normal" fullWidth label="User ID" name="userid" id="userid" type="text"
autoComplete="userid" component={TextField} />
<Field
variant="outlined" margin="normal" fullWidth id="password" name="password" label="Password" type="password"
autoComplete="current-password" component={TextField} />

<Button
type="submit" fullWidth variant="contained" color="primary"
className={this.state.classes.submit} disabled={isSubmitting || !isValid}
> Sign In
</Button>
</div>
</Container>
</Form>
)}
/>
)
}
}
export default LoginForm;

我是 React 的新手,我有谷歌但没有运气,这是我尝试过的代码,我调用了用户身份验证的 API 来验证用户 ID 和密码,请建议我以正确的方式调用 API。

enter image description here

最佳答案

我看到第一个调用是 0 个字节。

虽然我看不到你的 XHR 调用的细节,恕我直言,第一个调用不是 POST 动词而是一个 OPTION,因为你可能正在做网络 请求到后端域,该域不同于从 提供 React 应用程序的域| .

在 OPTION 调用中,服务器根据 CORS 授权或拒绝对端点的访问。所以,在我看来,没什么奇怪的。

关于reactjs - React Formik onSubmit RestAPI 调用两次,一次单击提交按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56703631/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com