【发布时间】:2020-05-04 08:42:55
【问题描述】:
有很多类似的问题,但对我没有任何帮助。每个 Axios 请求都会在我的 react redux 节点应用程序中触发两次。我正在使用 node 的 express 框架。如果我以登录页面为例,那么 Action 将从登录页面调度,例如:
import React, { useState } from "react";
import { connect } from "react-redux";
import { Link, Redirect } from "react-router-dom";
import { login } from "../../actions/auth";
import PropTypes from "prop-types";
const Login = ({ login, isAuthenticated }) => {
const [formData, setFormData] = useState({
email: "",
password: ""
});
const { email, password } = formData;
const onChange = e =>
setFormData({ ...formData, [e.target.name]: e.target.value });
const onSubmit = async e => {
e.preventDefault();
login({ email, password }); // this is action
};
//redirect if login
if (isAuthenticated) {
return <Redirect to="/dashboard" />;
}
return (
<section className="container">
<h1 className="large text-primary">Sign In</h1>
<p className="lead">
<i class="fa fa-user" aria-hidden="true"></i>Sign in your Account
</p>
<form className="form" onSubmit={e => onSubmit(e)}>
<div className="form-group">
<input
type="email"
placeholder="Email Address"
name="email"
value={email}
onChange={e => onChange(e)}
required
/>
</div>
<div className="form-group">
<input
type="password"
placeholder="Password"
name="password"
minLength="6"
value={password}
onChange={e => onChange(e)}
required
/>
</div>
<input type="submit" className="btn btn-primary" value="Login" />
</form>
<p className="my-1">
don't have an account? <Link to="/register">Sign Up</Link>
</p>
</section>
);
};
Login.propTypes = {
login: PropTypes.func.isRequired,
isAuthenticated: PropTypes.bool
};
const mapStateToProps = state => ({
isAuthenticated: state.auth.isAuthenticated
});
export default connect(mapStateToProps, { login })(Login);
而用户操作就像
export const login = ({ email, password }) => async dispatch => {
const config = {
headers: {
"Content-Type": "application/json"
}
};
const body = JSON.stringify({ email, password });
var res = "";
try {
//console.log('LOgin called'+ new Date());
res = await axios.post(baseURL + "/api/users/login", body, config);
// console.log(res.data.token);
//dispatch(setAlert('user login','primary'));
const { token } = res.data.token;
// Set token to ls
localStorage.setItem("token", token);
dispatch({
type: LOGIN_SUCCESS,
payload: res.data
});
dispatch(loadUser());
} catch (err) {
const errors = err.response.data.errors;
if (errors) {
errors.forEach(error => dispatch(setAlert(error.msg, "danger")));
}
dispatch({
type: LOGIN_FAIL,
payload: res.data
});
}
};
当我点击login 然后我登录但请求在api/users/login 发送了两次,但为什么?
我找不到原因,它与我的应用程序中的所有 axios 请求有关。
请求屏幕在这里
【问题讨论】:
-
您是如何检查请求执行了两次的?
-
在跨域情况下,您可能会看到额外的 OPTION 请求。
-
@ChristiaanWesterbeek 你是对的,但那是什么?
标签: node.js reactjs express react-redux