Laravel Response::json gives cross domain error i browser even if header is Access-Control-Allow-Origin:*

血红的双手。 提交于 2019-12-23 04:43:21

问题


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.

Does not work

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

Works

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.


回答1:


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' => '*'));
}

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.

Should be something like:

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', '*');

I found some issues with Cross Domain AJAX while using jQuery, it only works for me if I specify the domain instead of using *.

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



来源:https://stackoverflow.com/questions/18764309/laravel-responsejson-gives-cross-domain-error-i-browser-even-if-header-is-acce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!