Axios 对 Firebase Auth REST API 的发布请求产生 400 错误

Iga*_*gal 1 firebase firebase-authentication axios

我有一个 Axios 实例:

import axios from 'axios';

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

export default instance;
Run Code Online (Sandbox Code Playgroud)

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

<script>
  import axios from '../../axios-auth';
  ...
</script>
Run Code Online (Sandbox Code Playgroud)

在该 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);
          });
      }
Run Code Online (Sandbox Code Playgroud)

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

我尝试更改标题:

instance.defaults.headers.post["Access-Control-Allow-Origin"] = "localhost";
instance.defaults.headers.common["Content-Type"] = "application/json";
Run Code Online (Sandbox Code Playgroud)

但这没有帮助。

我在本地主机上工作,我看到默认情况下允许本地主机。我还尝试将 127.0.0.1 添加到列表中,但这也没有帮助。

我缺少什么?我怎样才能使这个请求起作用?

Ren*_*nec 6

如果您收到 400 错误,可能是因为您从API本身收到错误:

常见错误代码

EMAIL_EXISTS:该电子邮件地址已被其他帐户使用。

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

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

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

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

    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);
      }

    });
Run Code Online (Sandbox Code Playgroud)

请参阅https://github.com/axios/axios#handling-errors