PHP Nginx没有'Access-Control-Allow-Origin'错误



我正在使用 laravel 作为我的后端,并尝试使用 jQuery 向 Instagram api 发送请求,但我在 Chrome 浏览器检查器中响应正常时收到此错误

test?code=a3679b3…:1 XMLHttpRequest cannot load https://api.instagram.com/oauth/access_token. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://example.com' is therefore not allowed access.

这是我发送请求的代码

                $.ajax({
                method: 'POST',
                url: 'https://api.instagram.com/oauth/access_token',
                data: {
                    client_id: "client_id",
                    client_secret: "client_secret",
                    grant_type: "authorization_code",
                    redirect_uri: "example.com",
                    code: "{{$code}}"
                }
            });

我试图在我的 Nginx default.conf 文件中添加Access-Control-Allow-Origin,但这并没有解决我的问题。我该如何解决它?

此错误消息是由于 CORS。在浏览器中,您的 AJAX 请求应位于同一源上。因此,如果您使用的是 example.com,Chrome 将仅支持 AJAX example.com 请求。除非其他域(如 api.instagram.com(具有Acces-Control-Allow-Origin标头。您可以在此处阅读有关此内容的更多信息:

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

您可以尝试从后端访问Instagram。这样,您的AJAX请求将发送到同一源的后端,并且您的后端可以轻松访问Instagram的API。

您也可以尝试 dataType: "jsonp" ,在此答案中,您可以了解更多信息:

instagram jquery ajax type="GET, 无法绕过 CORS

相关内容

最新更新