【发布时间】: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