【问题标题】:Access-Control-Allow-Origin Request blocked from Localhost:3000 on firebaseAccess-Control-Allow-Origin 请求在 Firebase 上被 Localhost:3000 阻止
【发布时间】:2020-11-19 04:43:48
【问题描述】:

我在 axios 的 post 方法上收到错误代码:

错误:

Access to XMLHttpRequest at 'https://identitytoolkit.googleapis.com/v1/signupNewUser?key=AIzaSyAHO' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

代码:

 const authData = {
            email: email,
            password: password,
            returnSecureToken:true
        }
 axios.post('https://identitytoolkit.googleapis.com/v1/signupNewUser?key=AIzaSyAHOBs', authData)
                .then( response => {
                    console.log(response);
                    dispatch(authSuccess(response.data));
                })
                .catch(err => {
                    console.log(err);
                    dispatch(authFail(err));
                });

【问题讨论】:

标签: reactjs firebase react-redux axios


【解决方案1】:

我在 post 方法中使用了不同的 URL,即

https://identitytoolkit.googleapis.com/v1/signupNewUser?key=[API_KEY]

但正确的 URL 与您发布的相同,它甚至可以在不修改标题的情况下工作:

https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=[API_KEY]

代码 sn-ps:

export const auth = (email, password) => {
    return (dispatch) => {
      dispatch(authStart());
      const authData = {
        email: email,
        password: password,
        returnSecureToken: true,
      };
      const config = {
        headers: {
          "Content-Type": "application/json",
        },
      };
      axios.post(
        "https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=AIzaSyAHOBsv31rdWYhCr15gRS727QuCnajk2CU",
        authData,
        config
      )
        .then((response) => {
          console.log(response.data);
          dispatch(authSuccess(response.data));
        })
        .catch((err) => {
          console.log(err);
          dispatch(authFail(err));
        });
    };
  };

非常感谢

编码愉快:)

【讨论】:

    【解决方案2】:

    我正在做同样的课程并面临同样的错误。 看了半天,发现问题出在我们调用函数的地方(Auth.js文件)。

    当我们处理 onSubmit 方法时,我们像这样从 mapDispatchToProps 调用 onAuth 方法

    const mapDispatchToProps = dispatch =>{
        return {
            onAuth: (email, pass) => dispatch(actions.auth(email,pass))
        }
    }
    

    在课程视频中,提交处理程序是这样的。这是不正确的,并指示一个对象而不是一个字符串值。

    submitHandler = (event) => {
            event.preventDefault();
            this.props.onAuth(this.state.controls.email, this.state.controls.password);
        }
    

    正确的处理程序应该是这样的......

    submitHandler = (event) => {
            event.preventDefault();
            this.props.onAuth(this.state.controls.email.value, this.state.controls.password.value);
        }
    

    【讨论】:

      猜你喜欢
      • 2019-11-08
      • 2021-02-20
      • 2021-08-11
      • 1970-01-01
      • 2019-10-02
      • 2020-03-03
      • 2020-01-18
      • 2015-10-01
      相关资源
      最近更新 更多