【问题标题】:Axios post request to Firebase Auth REST API produces 400 errorAxios 向 Firebase Auth REST API 发布请求产生 400 错误
【发布时间】:2020-02-16 05:04:21
【问题描述】:

我有一个 Axios 的实例:

import axios from 'axios';

const instance = axios.create({
  baseURL: 'https://identitytoolkit.googleapis.com/v1'
});

export default instance;

然后我将它导入到我的 signup.vue 文件中:

<script>
  import axios from '../../axios-auth';
  ...
</script>

在那个 Vue 文件中,我有一个注册表单,一旦我点击提交按钮,它就会运行以下方法:

onSubmit() {
        const formData = {
          email: this.email,
          age: this.age,
          password: this.password,
          confirmPassword: this.confirmPassword,
          country: this.country,
          hobbies: this.hobbyInputs.map(hobby => hobby.value),
          terms: this.terms
        };
        console.log(formData);
        axios.post('/accounts:signUp?key=my_key_goes_here', {
          email: formData.email,
          password: formData.password,
          returnSecureToken: true
        })
          .then(res => {
            console.info(res);
          })
          .catch(error => {
            console.error(error);
          });
      }

我收到 403 错误 - 禁止 400 错误 - 错误请求。

我尝试更改标题:

instance.defaults.headers.post["Access-Control-Allow-Origin"] = "localhost";
instance.defaults.headers.common["Content-Type"] = "application/json";

但这并没有帮助。

我在 localhost 工作,我看到默认情况下允许使用 localhost。我也尝试将 127.0.0.1 添加到列表中,但这也没有帮助。

我错过了什么?我怎样才能使这个请求生效?

【问题讨论】:

  • Access-Control-Allow-Origin 是一个响应头。它必须在服务器端设置,而不是在发出请求的前端 JavaScript 代码中。如果您收到 403 响应,预计它不会有 Access-Control-Allow-Origin 响应标头。通常,服务器只将您的应用程序集标头添加到成功响应中——2xx 和可能的 3xx 响应——而不是 4xx 或 5xx 错误响应。而且您所做的任何 CORS 配置都不会导致服务器响应 403。因此,无论实际导致 403 错误的原因是什么,它都与 CORS 配置无关。
  • @sideshowbarker 我看到一条错误消息,说它是 CORS。由于某种原因,现在我看不到它,但现在我有一个 400 错误 - 错误的请求。我看到请求转到 https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=my_api_key,根据 Firebase 文档,它应该是 API 端点。

标签: firebase firebase-authentication axios


【解决方案1】:

如果您收到 400 错误,可能是因为您收到了来自 API 本身的错误:

常见错误代码

EMAIL_EXISTS:该电子邮件地址已被另一个帐户使用。

OPERATION_NOT_ALLOWED:此项目禁用密码登录。

TOO_MANY_ATTEMPTS_TRY_LATER:由于异常活动,我们已阻止来自此设备的所有请求。请稍后再试。

事实上,这些错误返回的 HTTP 状态码为 400。

您可以通过使用 axios 执行以下操作来查看确切的响应消息(例如 EMAIL_EXISTS):

    axios.post('/accounts:signUp?key=my_key_goes_here', {
      email: formData.email,
      password: formData.password,
      returnSecureToken: true
    })
      .then(res => {
        console.info(res);
      })
    .catch(error => {
      if (error.response) {
        // The request was made and the server responded with a status code
        // that falls out of the range of 2xx
        console.log(error.response.data);
      } else if (error.request) {
        console.log(error.request);
      } else {
        console.log("Error", error.message);
      }

    });

https://github.com/axios/axios#handling-errors

【讨论】:

  • 谢谢,确实有帮助!显然,因为我只是在测试它,所以我使用了一个弱密码,只有 3 个字符,而 Firebase 至少需要 6 个字符。一旦更改为 6 - 就像一个魅力。再次感谢您!
【解决方案2】:

我同意你的观点,因为我尝试了很多方法但没有得到结果。因此,我试图更改代码。

您需要对代码进行两处更改。

1] 您需要评论the instance.defaults.headers.post["Access-Control-Allow-Origin"] = "localhost";,因为您提供的是全局身份验证。因为,firebase 提供身份验证功能,您正在将 Web 应用程序与 REST API 连接。

2] 需要在 axios.post() 方法中添加{ headers: {'Content-Type': 'application/json' } 以防止出现CORS错误。 按照这种方法,我希望你能得到相应的输出。 快乐编码!

【讨论】:

    【解决方案3】:

    【讨论】:

      【解决方案4】:

      任何人在未来来到线程。我遇到了这个问题,在调试中迷失了方向,并使用了 fetch。这很烦人,花了我一天的时间,但我让 axios 工作了。这是代码。
      常量数据 = JSON.stringify({ idToken:authContext.token, 密码:输入新密码, returnSecureToken:假, });

      // Send the valid password to the endpoint to change password
      axios
        .post(
          "https://identitytoolkit.googleapis.com/v1/accounts:update?key=[Your Key]",
          data,
          {
            headers: {
              "Content-Type": "application/json",
            },
          }
        )
        .then((response) => {
          console.log(response.data);
        })
        .catch((err) => {
          console.log(err.message);
        });
      
      • 记得Stringify您要发送的数据。在 http 请求之外对其进行字符串化,然后传递该变量。不知道为什么,但这有帮助!
      • 最后记得在向 firebase 发送请求时添加标头。确保 axios.post 在同一行。我的格式化程序给出了一个换行符,这也是导致错误的原因。
      • 希望对您有所帮助:)

      【讨论】:

        猜你喜欢
        • 2020-11-19
        • 2021-03-31
        • 1970-01-01
        • 2022-11-12
        • 1970-01-01
        • 2018-10-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多