拉维尔5号+;AngularJS跨域CORS

拉维尔5号+;AngularJS跨域CORS,angularjs,cors,laravel-5,Angularjs,Cors,Laravel 5,我到处寻找答案,但到目前为止什么都没有找到。堆栈上列出的所有解决方案都没有被证明是足够的 我在我的laravel日志中没有任何错误,我只得到标准: XMLHttpRequest cannot load http://api.domain.dev/post/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://domain.dev' is therefore no

我到处寻找答案,但到目前为止什么都没有找到。堆栈上列出的所有解决方案都没有被证明是足够的

我在我的laravel日志中没有任何错误,我只得到标准:

XMLHttpRequest cannot load http://api.domain.dev/post/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://domain.dev' is therefore not allowed access.
拉威尔控制器:

<?php namespace App\Http\Controllers;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Post;
use App\Tag;
use Illuminate\Http\Request;

class PostController extends Controller {

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {

        $posts = Post::with('user', 'tags')->get();

        return response()->json($posts);
    }
}
我不知道从这里到哪里去。 从正常的
header()
实现到使用laravel cors包通过过滤器和控制器中的_构造来实现,我已经尝试了一切。
我还选择了服务器配置路径,并尝试将标题添加到.htaccess和virtualhost配置中。

在返回
标题(“访问控制允许源代码:”)之前添加这一行

你的代码应该是

public function index()
{
    $posts = Post::with('user', 'tags')->get();
    header("Access-Control-Allow-Origin: *");
    return response()->json($posts);
}

我对laravel没有很好的了解,但我的建议是,请求头可以访问REST方法(GET、POST、PUT、DELTE)和特定域的来源,从该域以以下方式发出请求,或者设置为“*”(它允许任何域)


如果在调用跨源XHR请求时使用,javascript会首先向给定URL发出选项请求。如果您的路由中没有添加此方法,那么它会弹出一个404页面,该页面没有ACAO头,因此不会发送具体的POST请求,因为javascript认为不允许这样做。

添加

<?php header("Access-Control-Allow-Origin: *"); ?>


到public/index.php,如果它在blue bells建议的函数中不起作用

请在您的public/index.php中添加以下行:

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token'); // allow certain headers 

看,如果这样行的话。

我也有同样的问题,但是使用jQuery,我花了几周时间才找到一个好的解决方案

在我的案例中,创建一个中间件来设置标题是一个完美的解决方案

创建Cors中间件:App\Http\middleware\Cors.php

namespace App\Http\Middleware;

use Closure;

class Cors
{

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request)
            ->header('Access-Control-Allow-Origin', $_SERVER['HTTP_ORIGIN'])
            // Depending of your application you can't use '*'
            // Some security CORS concerns 
            //->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', 'POST, OPTIONS')
            ->header('Access-Control-Allow-Credentials', 'true')
            ->header('Access-Control-Max-Age', '10000')
            ->header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');
    }
}
记住在App\Http\Kernel中设置Cors别名

protected $routeMiddleware = [
    ...
    'cors' => \App\Http\Middleware\Cors::class,
];
在路由内部,您可以将中间件与组一起使用,也可以直接连接到特定路由,例如:

Route::match(['post', 'options'], 'api/...', 'Api\XController@method')->middleware('cors');
如果有人对jQuery有这个问题,我建议使用$.ajax,而不是$.get、$.post。当您使用这种方法时,jQuery使用XMLHttpRequest发送数据,并将内容类型设置为application/x-www-form-urlencoded,这是不可能改变的,所以使用Ajax

e、 g:

请记住:如果您在请求头上使用application/json,则必须提供“OPTIONS”方法来进行预飞行


关于CORS的更多信息:

我做了些什么,但不确定这是否是最好的解决方案,但没有CORS

1.使用
ng build--prod正常构建角度

2.将
angular/dist
的内容移动到
laravel/public

3.然后在
laravel/routes/web.php

Route::prefix('api')->group(function () {
    Route::get('/', function () {
    return view('welcome');
    });
});
Route::get('/{params?}', function () {
//    return view('welcome');
    include_once '../public/index.html';
})->where('params', '(.*)');

现在所有的请求都到了Laravel,如果它能用一个路由捕捉到请求,那么这个路由就会起作用,否则它会把请求传递给angular

我知道你的意思,但什么也不做,只是在chrome控制台中返回相同的错误。@user2298680我也有同样的问题。但我通过标题(“Access Control Allow Origin:*”)解决了这个问题;。。。让我们看看有人会解决你的问题。angular.js应用程序从其他域登录时,我的Laravel 5.0 API将丢失会话。这些angular.js应用程序托管在其他域和其他服务器中。您是否尝试过使用包发送跨源资源共享头?还有一件事。如果在控制器中返回一个新的响应,
Resnpose::json()
Response::make()
,等等。您需要再次设置头(第三个参数),因为中间件设置的头不会传递给新的响应实例。在我使用凭据更改时:true到false,它会起作用
namespace App\Http\Middleware;

use Closure;

class Cors
{

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request)
            ->header('Access-Control-Allow-Origin', $_SERVER['HTTP_ORIGIN'])
            // Depending of your application you can't use '*'
            // Some security CORS concerns 
            //->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', 'POST, OPTIONS')
            ->header('Access-Control-Allow-Credentials', 'true')
            ->header('Access-Control-Max-Age', '10000')
            ->header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');
    }
}
protected $routeMiddleware = [
    ...
    'cors' => \App\Http\Middleware\Cors::class,
];
Route::match(['post', 'options'], 'api/...', 'Api\XController@method')->middleware('cors');
        $.ajax({
            type: 'POST',
            url: 'www.foo.bar/api',
            contentType: "application/json",
            xhrFields: {
                // The 'xhrFields' property sets additional fields on the XMLHttpRequest.
                // This can be used to set the 'withCredentials' property.
                // Set the value to 'true' if you'd like to pass cookies to the server.
                // If this is enabled, your server must respond with the header
                // 'Access-Control-Allow-Credentials: true'.
                withCredentials: true

            },

            headers: {
                // Set any custom headers here.
                // If you set any non-simple headers, your server must include these
                // headers in the 'Access-Control-Allow-Headers' response header.
                'Accept': 'application/json'
            },



            data: '{"some":"json data"}',
            success: function (data) {
                console.log('AJAX version');
                console.log("Works!")
            },
        });
Route::prefix('api')->group(function () {
    Route::get('/', function () {
    return view('welcome');
    });
});
Route::get('/{params?}', function () {
//    return view('welcome');
    include_once '../public/index.html';
})->where('params', '(.*)');