客户端服务器号'Access-Control-Allow-Origin'当从自己的域返回json时


Client Server No 'Access-Control-Allow-Origin' when returning json from own domain

我有一个应用程序,前端使用angular/js,后端使用php。两者都使用同一个域(www.foo.bar)。

我已经在我的后端实现了领英身份验证。在前端,我输入

     $http({
            method: 'POST',
            url: 'http://foo.bar/api/authenticate',
            headers: { 'Content-Type' : 'application/x-www-form-urlencoded' }
        }).success(function(outcome){
            console.log("success");
        }).error(function(outcome){
            console.log('error');
        });

我的服务器然后用linkedin对用户进行身份验证(这包括一些重定向),最后返回一个json,其中包含从linkedin检索到的基本个人资料信息。

如果我直接访问api:bar/api/authenticate,它工作得很好,我可以看到json。如果我在前端使用ajax请求调用它,我会得到

XMLHttpRequest cannot load https://www.linkedin.com/uas/oauth2/authorization?blablabla No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://foo.bar' is therefore not allowed access. 

例外。

任何想法?

编辑:在研究了可能的解决方案后,我缩小了问题的范围,并或多或少地解决了它。问题不在于我不能从我自己的api访问json文件,问题是我在ajax调用中做了重定向。

public function authorize(){
    return Redirect::away("https://www.linkedin.com/uas/oauth2/authorization?response_type=linkedinApiData&redirect_uri=http://foo.bar/api/members/authenticated");
}

我在想,如果这重定向到另一个api调用,完成授权并返回一个json对象,那就好了,但后来我得到了之前提到的异常(来自linkedin我猜)。

我有一个临时的解决方案,就是使用ahttp://foo.bar/api/..>,它处理认证请求,重定向,并最终重定向到我必须去的页面,并在会话中存储结果json。当下一页加载时,我要求后端返回此会话的内容。

是否有可能做一个帖子,与身份验证(包含重定向,需要领英认证),然后从我自己的服务器返回json(工作,没有访问头问题?

域名只是来源的一部分。整个原点:

  • 完整主机名

…必须匹配。

foo.barwww.foo.bar不一样。

要么是一致的关于您正在使用的主机名(一般来说,重定向所有请求从example.comwww.example.com或反之亦然是一个好主意)或实现一种手段来规避同源策略。

您必须在http://foo.bar/api/authenticate服务中添加Access-Control-Allow-Origin头。

样本;

<?php
header('content-type: application/json; charset=utf-8');
header("access-control-allow-origin: *"); 
?>

如果你想设置一个特定的域,你必须改变*节http://www.foo.bar或www.foo.bar