简体   繁体   中英

Cors error in React with axios but not with fetch

I'm trying to query my Azure search portal from a react frontend. I have enabled all cors on the correct index. When I query with fetch, I get the data just fine, however when I query with axios I get the following error

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.

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

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 = 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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