【问题标题】:firebase authentication rest API request with axios带有 axios 的 firebase 身份验证 rest API 请求
【发布时间】:2021-10-05 11:41:37
【问题描述】:

我正在尝试编写函数以使用电子邮件和密码登录用户。

使用 Axios 和 firebase rest API。

这就是 Axios 实例的样子,真的很简单吧? ...

 const authUrl = `https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=${DATABASE_SECRET}`;
const baseURL = "https://beauty-wonderland-e913c-default-rtdb.firebaseio.com";

export const getAxios = (token = null) => {
  const config = {
    baseURL: baseURL,
    headers: {
      "Content-Type": "application/json",
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Methods": "DELETE, POST, GET, OPTIONS",
      "Access-Control-Allow-Headers":
        "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With",
    },
    timeout: 10000,
  };

  if (token !== null) {
    // config.headers.Authorization = `Bearer ${token}`;

    config.baseURL = authUrl;
    config.withCredentials = true;

  }

  let instance = axios.create(config);

  instance.interceptors.request.use(
    (request) => {
      return request;
    },
    (error) => {
      console.log("axios error: ", error);
      return Promise.reject(error);
    }
  );

  instance.interceptors.response.use((response) => {
    return response;
  });

  return instance;
}; 

此代码运行良好、灵活,可以发送任何类型的请求,但在身份验证方面,发送用户数据存在问题:电子邮件和密码。

const loginHandler = async () => {
    const response = await getAxios("/").post("", {
      body: JSON.stringify({
        email: "example@example.com",
        password: "password",
        returnSecureToken: true,
      }),
    });

    const outPut = processResponse(response);

    console.log(outPut);
}

所以我猜这部分有问题

{
          body: JSON.stringify({
            email: "a@a.com",
            password: "123456",
            returnSecureToken: true,
          }),
        });
 }

如果 fetch 函数以这种方式工作

fetch(   
`https://identitytoolkit.googleapis.com/v1/accounts:signInWithPasswordkey=${DATABASE_SECRET}`,
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          email: "example@example.com",
          password: "password",
          returnSecureToken: true,
        }),
      }
    );

为什么axios会报如下错误:

XMLHttpRequest at ... from origin 'http://localhost:19006' 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.

请注意其他使用 axios 的 get 和 post 请求有效,alo 身份验证适用于 fetch,只有 axios 显示此类错误,请发布其他资源以了解有关 firebase rest API 和 Axios 用例的更多信息。

这是错误的样子

【问题讨论】:

    标签: reactjs firebase react-native firebase-authentication axios


    【解决方案1】:

    “getAxios”函数返回的 axios 实例中的 baseURL 是 https://beauty-wonderland-e913c-default-rtdb.firebaseio.com,而不是 Auth REST API url。它应该是authUrl。在 fetch 中,您已经对 URL 进行了硬编码,因此 URL 肯定是正确的。

    编辑:

    删除那些无关的标题。您只需要按照文档的内容类型。当我遇到这些时,我遇到了同样的 CORS 错误。

    const config = {
        baseURL: baseURL,
        headers: {
          "Content-Type": "application/json",
        },
        timeout: 10000,
      };
    

    【讨论】:

    • 从源“<a href="/default/index/tourl?u=aHR0cDovL2xvY2FsaG9zdDoxOTAwNg%3D%3D" rel="nofollow" target="_blank">localhost:19006</a>”访问 XMLHttpRequest 在“<a href="/default/index/tourl?u=aHR0cHM6Ly9pZGVudGl0eXRvb2xraXQuZ29vZ2xlYXBpcy5jb20vdjEvYWNjb3VudHM6c2lnbkluV2l0aFBhc3N3b3JkP2tleT0lNUJUT1BfU0VDUkVUJTVELw%3D%3D" rel="nofollow" target="_blank">identitytoolkit.googleapis.com/v1/…</a>”已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:否“访问-请求的资源上存在 Control-Allow-Origin' 标头。 这是一个错误,所以那里有正确的 url,这段代码应该有意义 config.baseURL = authUrl;
    • @BekaBatmanashvili 你能分享你的控制台截图吗?
    • 已编辑帖子,上传图片,希望质量足够好,如果您还需要知道headers: { Access-Control-Allow-Headers: "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With" Access-Control-Allow-Methods: "GET, POST, PATCH, PUT, DELETE, OPTIONS" Access-Control-Allow-Origin: "*" Authorization: [top_SECRET] Content-Type: "application/json"}中的内容
    • @BekaBatmanashvili 您需要删除那些额外的标题。检查更新的答案。
    猜你喜欢
    • 2019-08-17
    • 2019-12-22
    • 2019-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-21
    • 1970-01-01
    • 2014-10-12
    相关资源
    最近更新 更多