【问题标题】:Laravel - Vue Axios CORS policyLaravel - Vue Axios CORS 策略
【发布时间】:2021-02-22 17:23:28
【问题描述】:

请求

axios.get("https://maps.googleapis.com/maps/api/geocode/json?latlng="+this.currentLocation.lat+","+this.currentLocation.lng+"&key="+this.apiKey).then((response) => {
                        if (this.town === response.data.results[0].address_components[2].long_name){
                            return
                        }
                        else{
                            this.town = response.data.results[0].address_components[2].long_name
                            this.getSuggested();
                            this.getAllEvents();
                        }
                        
                }).catch(er => {
                    console.log(er)
                })

当我尝试获取某个位置的城镇时,我收到此错误

CORS 策略已阻止从源“http://localhost:8000”访问“API Route”处的 XMLHttpRequest:预检中 Access-Control-Allow-Headers 不允许请求标头字段 x-requested-with回应。

当我删除时

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

来自 bootstrap.js,请求工作正常。

这到底是什么问题?

【问题讨论】:

    标签: laravel vue.js google-maps axios cors


    【解决方案1】:

    如果您发送请求的任何服务器包含不是CORS-safelisted 的标头,通常默认情况下都会拒绝它。

    window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
    

    此代码告诉 axios 为每个请求附加一个自定义标头。因此,您的请求正在发送带有非安全列表的标头,服务器不允许,因此您收到错误。

    要允许请求,必须将服务器配置为允许自定义标头。

    【讨论】:

      猜你喜欢
      • 2021-10-13
      • 2020-08-27
      • 2018-07-20
      • 2021-05-08
      • 2020-06-02
      • 2021-09-29
      • 1970-01-01
      • 2021-04-19
      • 2019-10-01
      相关资源
      最近更新 更多