首页 > 解决方案 > 在 '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;

标签: javascriptfirebasevue.jsaxios

解决方案


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");.


推荐阅读