Laravel响应:: JSON给人即使头是访问控制 - 允许 - 产地跨域的错误我的浏览器:*我的、给人、产地、访问控制

2023-09-11 01:16:45 作者:胖狗

我得到了这个Laravel 4的问题,真的困惑了我。我创建同一个控制器上这两种方法。在宣布该控制器是宁静的。 Ajax请求是从不同的域。

I got this Laravel 4 problem that is really confusing to me. I Created these two methods on the same controller. The controller in declared to be restful. The ajax request is from a different domain.

不工作

public function getOwnlist(){
    $test = User::with(array("images", "images.category"))->find(Auth::user()->id);
    return Response::json($test, 200, array('Access-Control-Allow-Origin' => '*'));
}

作品

public function getLatest(){
        $images = DB::table("images")->where("public","=","1")->orderBy("created_at")->take(10)->get();
        return Response::json($images, 200, array('Access-Control-Allow-Origin' => '*'));
}

在浏览器中得到一个标准的跨域错误。

The browser get a the standard cross domain error.

推荐答案

这个例子对我的作品,你可以试试这个。

This example works for me you may try this.

public function getOwnlist(){
   $images = User::with('images.category')->find(Auth::getUser()->getAttribute('id'));
   return Response::json($images, 200, array('Access-Control-Allow-Origin' => '*'));
}

另外,我强烈建议这些设置在你的控制器基础的构造函数,而不是设置标头中的每一个响应。或者你也可以创建一个只服务的API,并从它延伸。

Also, I highly recommend setting those on the constructor of your Controller Base instead of setting the headers in each response. Or you can create one only to serve API and extend from it.

应该是这样的:

protected $response; // This is a global variable on you BaseController

// This goes on your BaseController constructor 
$this->response = Response::make();
$this->response->headers->add(array('Access-Control-Allow-Origin', '*');

我发现跨域AJAX的一些问题,同时使​​用jQuery,它仅适用于我,如果我指定的域名,而不是使用 *

这是锋模型的详细信息: http://laravel.com/docs/eloquent#querying-relations

More information on Eloquent Models: http://laravel.com/docs/eloquent#querying-relations