node.js - 每个 axios 请求在 React-Redux 应用程序中都会触发两次?

标签 node.js reactjs express react-redux

有很多类似的问题,但没有什么对我有帮助。每个 Axios 请求在我的 React Redux Node 应用程序中都会触发两次。我正在使用 Node 的express框架。如果我以登录页面为例,那么操作将从登录页面调度,例如:

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 请求有关。 请求屏幕在这里request screen from firebug

最佳答案

对于 Axios 发出的每个请求,您都会看到一个额外的 OPTION 请求。该额外的 OPTION 请求由您的浏览器执行,因为它检测到跨源。以下是执行额外 OPTION 请求的原因和方式:Why is an OPTIONS request sent and can I disable it?

关于node.js - 每个 axios 请求在 React-Redux 应用程序中都会触发两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59787719/

相关文章:

reactjs - Reactjs 中的 Antd 文件上传验证

express - 如何将jwt token 存储在localStorage中,并使用express中的 header 将其发送回服务器?

javascript - express JS : serving files out of memory vs serving static files

javascript - 运行 AWS Lambda 函数,无论 cron 事件如何(并检查 Mongo DB 连接是否已成功建立)?

javascript - 如何在axios上使用react选择参数?

javascript - 导入多个集合(nodejs、mongodb)

node.js - Express:POST 请求后 Req.body 未定义

node.js - 如何使用express和typeorm正确更新实体

node.js - 如何运行谷歌助手比特币信息示例 webhook index.js

reactjs - 将属性传递给组件与通过 redux store 访问