简体   繁体   English

React 中的 Cors 错误与 axios 而不是 fetch

[英]Cors error in React with axios but not with fetch

I'm trying to query my Azure search portal from a react frontend.我正在尝试从 React 前端查询我的 Azure 搜索门户。 I have enabled all cors on the correct index.我在正确的索引上启用了所有 cors。 When I query with fetch, I get the data just fine, however when I query with axios I get the following error当我使用 fetch 查询时,我得到的数据很好,但是当我使用 axios 查询时,我收到以下错误

Access to XMLHttpRequest at 'maskedurl' from origin 'http://localhost:3000' 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.从源“http://localhost:3000”访问“maskedurl”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:不存在“Access-Control-Allow-Origin”标头在请求的资源上。

This is my component这是我的组件

import React from 'react';
import azure from '../apis/azure';

class GeoSearch extends React.Component {
    state = {
        lat: '',
        lon: ''
    }

    componentDidMount(){
        window.navigator.geolocation.getCurrentPosition(
          position => this.setState({ lat: position.coords.latitude, lon: position.coords.longitude }),
          err => this.setState({ errorMessage: err.message }),
        );
    };

    onNavLoad = async (lon, lat) => {
        const response = await azure.post('/', {
            params: { 
                "filter": "geo.distance(Location, geography'POINT(-6.184120 53.605190)') le 4",
                "Access-Control-Allow-Origin": "*"
            },
            headers: { 
                'api-key': 'apikeymasked',
                "Access-Control-Allow-Origin": "*"
            },
        });


        console.log(response);
    }
    
    render() {
        if (this.state.lat){
            return (
                <div>
                    <h1>Geo Search</h1>
                    <div>{this.state.lon}</div>
                    <div>{this.state.lat}</div>
                    <button onClick={this.onNavLoad}>Click</button>
                </div>
            )
        }
        return (
            <div>
                <h1>Geo Search Loading</h1>
            </div>
        );
    }
}

export default GeoSearch;

This is my axios.create method in a file called azure.js which is in a sibling folder of the component folder called apis这是我在名为 azure.js 的文件中的 axios.create 方法,该文件位于名为 apis 的组件文件夹的同级文件夹中

import axios from 'axios';

export default axios.create({
    baseURL: 'maskedurl',
    params: {
        "search": "",
        "select": "name",
        "count": "true"
    },
    headers: {
        "Access-Control-Allow-Origin": "*"
    }
}); 

This doesn't work.这不起作用。

However when I switch the axios in the onNavLoad function to a fetch like so, it works perfectly.但是,当我将 onNavLoad 函数中的 axios 切换为这样的 fetch 时,它运行良好。

    onNavLoad = async (lon, lat) => {


    var myHeaders = new Headers();
    myHeaders.append("api-key", "apikeymasked");
    myHeaders.append("Content-Type", "application/json");

    var raw = JSON.stringify({"search":"","filter":"geo.distance(Location, geography'POINT(-6.184120 53.605190)') le 50","select":"name","count":"true"});

    var requestOptions = {
      method: 'POST',
      headers: myHeaders,
      body: raw,
      redirect: 'follow'
    };

    const response = fetch("maskedurl", requestOptions)
      .then(response => response.json())
      .then(result => console.log(result.value))
      .catch(error => console.log('error', error));

    console.log(response);
}

Any ideas?有任何想法吗?

Generally its server site issue, But you can override this issue from client side using PROXYURL通常是它的服务器站点问题,但您可以使用 PROXYURL 从客户端覆盖此问题

 const proxyURL = "https://cors-anywhere.herokuapp.com/"; const requestURL = YOUR URL; const response = fetch(proxyURL + requestURL, requestOptions)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM