如何在reactjs中设置标头请求

时间:2017-01-06 03:20:14

标签: python security reactjs

我试图设置Access-Control-Allow-Origin以便能够跳过以下错误:

XMLHttpRequest cannot load http://www.test.dev:8090/glasses/import/log/qa/qa2/20170106?headers%5BAc…llow-Headers%5D=Origin%2C%20X-Requested-With%2C%20Content-Type%2C%20Accept. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.test.dev:3000' is therefore not allowed access.

但我没有得到理想的结果。客户端在reactjs中实现,并向python Web应用程序发送get请求。这是我的代码:

class InfoBox extends Component {
  constructor() {
    super();
    this.state = {items:[]};
  }

  componentDidMount() {
    Request.get('http://www.test.dev:8090/glasses/import/log/qa/qa2/20170106', {
      headers:{
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept"
      }
    }) 
      .then((response) => {
      this.setState({items:response});
    });
  }
  render() {
      const content = this.state.items.map(function(item) {return <div>{item}</div>});
      return (
        <div >{content}</div>
      );
  }
}

1 个答案:

答案 0 :(得分:1)

未从client端启用CORS,而是从服务器端启用CORS。

在正常http请求中,浏览器最初会发送选项请求,以验证源是否具有访问资源的权限。服务器将使用Access-Control-Allow-Origin标头回复。如果在标题中设置了源,则浏览器将发送适当的PUT, POST, GET, DELETE请求。

您需要在python server响应

中指定这些标头