javascript - 在 'https://identitytoolkit.googleapis.com/v1/accounts:/signUp? 访问 XMLHttpRequest?来自 'http://localhost:8080' 的来源已被阻止
问题描述
从源“http://localhost:8080”访问“https://identitytoolkit.googleapis.com/v1/accounts:/signUp?key=AIzaSyDvZN5PKdB_b9jX-5rA-t9e3KSxJ-qtkdU”的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:没有“Access-Control-Allow-Origin”
我正在尝试在 vue.js 中使用 Axios 在 firebase 中创建一个新用户,并且出现上述错误。这是我的代码示例。
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('signUp?key=AIzaSyDvZN5PKdB_b9jX-5rA-t9e3KSxJ-qtkdU', {
email: formData.email,
password: formData.password,
returnSecureToken: true,
})
.then((res) => {
console.log(res)
})
.catch((error) => {
console.log(error)
})
}
这是我的默认 axios 实例代码。
import axios from 'axios'
const instance = axios.create({
baseURL: 'https://identitytoolkit.googleapis.com/v1/accounts:'
});
instance.defaults.headers.common['Access-Control-Allow-Headers'] = 'X-Requested-With, content-type';
instance.defaults.headers.common['Access-Control-Allow-Origin'] = 'X-Requested-With, content-type';
export default instance;
解决方案
CORS 是一个非常烦人的错误,实际上它是一场噩梦。
解决此问题的一种方法是使用代理,例如https://cors-anywhere.herokuapp.com。
获取示例:
var proxyUrl = 'https://cors-anywhere.herokuapp.com/',
targetUrl = 'https://request-url.com'
fetch(proxyUrl + targetUrl)
.then(blob => blob.json())
.then(data => {
var stringed = JSON.stringify(data);
const res = JSON.parse(stringed);
// Use res to access JSON
})
.catch(e => {
console.log(e);
return e;
});
当然,这个例子只是为了获取,但我相信你可以修改它以使用 axios。
如果您使用的是 NodeJS,请添加const fetch = require("node-fetch");
.
推荐阅读
- python-3.x - TF Keras 模型服务 REST API JSON 输入格式
- typescript - NestJS 无法解析模块内部的依赖关系
- javascript - 游戏不工作,但我的代码看起来不错
- javascript - 使用 worker 终止实现 JS WebWorkers Job Queue
- c - 从 .txt 文件中读取内容并使用 fscanf 存储在结构中
- python - Scrapy - TypeError:只能将str(不是“list”)连接到str
- c++ - QT5 C++,有没有办法可以在 qlist 容器中获取小部件的当前文本
- r - 如何在不使用库的情况下将模型摘要的每一列存储在 R 的列表中
- c++ - 在 c++ 的 SetWindowsHookEx 函数中
- css - 使用 CSS 动画触发第二个动画关键帧(或永久移动 div)?