fetch()导致“跨域请求被阻止”错误(在浏览器中),但在Postman中成功

时间:2019-07-16 13:33:17

标签: javascript reactjs firefox cors fetch-api

我正在尝试向Google的Place Search API发出fetch()请求。

fetchPlaces() {
        //fetch nearby restaurants using Google's Place Search API

        let params = {
            key: <REMOVED FOR STACKOVERFLOW>,
                //location: latitude, longitude
            location: `${this.state.coords.latitude},${this.state.coords.longitude}`,
                //radius (in meters), 32186.9m. = 20mi.
            radius: '32186.9',
            type: 'restaurant'
        }
        const URL = `https://maps.googleapis.com/maps/api/place/nearbysearch/json?key=${params.key}&location=${params.location}&radius=${params.radius}&type=${params.type}`
        fetch(URL).then(res => console.log(res))
    }

上面的代码导致以下CORS错误:

跨域请求被阻止:“同源起源”策略禁止读取位于https://maps.googleapis.com/maps/api/place/nearbysearch/json .... 387420299999995,-112.0504627&radius = 32186.9&type = restaurant的远程资源。 (原因:CORS标头“ Access-Control-Allow-Origin”缺失)

以及此TypeError: TypeError:尝试获取资源时出现NetworkError。

我正在从本地主机发出请求:3000 我已经在Chrome和Firefox中进行了测试,但均无法正常工作。

但是,当我从Postman向API发送请求时,我会得到预期的JSON响应。

0 个答案:

没有答案