ReactJS:没有带有 XMLHttpRequest 的“Access-Control-Allow-Origin"标头 [英] ReactJS: No 'Access-Control-Allow-Origin' header with XMLHttpRequest

查看:52
本文介绍了ReactJS:没有带有 XMLHttpRequest 的“Access-Control-Allow-Origin"标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码给出了下一个错误.我已经设置了标题.我发现问题出在 CORS 中,但找不到如何使其工作.在评论中,我尝试使用 axios 发送请求,但下面的请求是使用 XMLHttpRequest 发出的,我虽然处理了 cors.

The code below gives the next error. I've set the header. I found the problem lies in CORS but couldn't find how to make it work. In the commented I tried to send request with axios but below the request is made with XMLHttpRequest which I though takes care of cors.

import * as React from 'react';
import GoogleLogin from 'react-google-login';
//import axios from 'axios';

export default class GoogleAuth extends React.Component<{}, {}>{
  constructor(props: {}){
    super(props);

    this.handleResponse = this.handleResponse.bind(this);
  }

  handleResponse(response){
    console.log(response);
    console.log(response.googleId);

    //if(response.googleId){
      // let config = {
      //   headers: {
      //     'Access-Control-Allow-Origin': '*',
      //     'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept'
      //   },
      //
      // };
      //
      // axios.get('https://picasaweb.google.com/data/feed/api/user/' + response.googleId + '?kind=album&access=public', config)
      // .then(function(response2){
      //   console.log(response2);
      // })
      // .catch(function(error){
      //   console.log(error);
      // });

    //}

    let xhttp = new XMLHttpRequest();
    xhttp.setRequestHeader('Access-Control-Allow-Headers', '*');

    xhttp.onreadystatechange = function(e){
        console.log(this);
        if(xhttp.readyState === 4 && xhttp.status === 200){
          console.log(this.response);
        }
    };

    xhttp.open('get', 'https://picasaweb.google.com/data/feed/api/user/' + response.googleId + '?kind=album&access=public',true);
    xhttp.send();
  }

  render(){
    return(
      <GoogleLogin
        clientId="890876118034-jra8v99vqbgf3e0u5eu29lit2bm66lqi.apps.googleusercontent.com"
        buttonText="Login"
        onSuccess={this.handleResponse}
        onFailure={this.handleResponse}
      />
    );
  }
}

推荐答案

您需要允许白名单标题 "http://localhost:3000"在您的 Google 开发者帐户中.

You need to allow the whitelist header "http://localhost:3000" on you Google developer account.

尝试更改 ajax 调用中的 dataType: 'jsonp'.

Try changing the dataType: 'jsonp' in your ajax call.

这篇关于ReactJS:没有带有 XMLHttpRequest 的“Access-Control-Allow-Origin"标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆