Laravel Cors(中间件不起作用) [英] Laravel Cors (Middleware NOT working)

查看:961
本文介绍了Laravel Cors(中间件不起作用)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近尝试在Laravel 5.4中启用CORS,但不幸的是,它不起作用.我在下面包含了代码和它给我的错误.谁能帮忙找出为什么它不起作用?我已经传递了必需的标题.

I recently tries enabling CORS in Laravel 5.4 but unfortunately it doesn't want to work. I have included the code and the error that it's giving me below. Can anyone help finding out why it isn't working? I have passed the required headers.

出于示例目的,我已将我的域重命名为domain.uk,但我还不想将其域公开为正在开发中.

I have renamed my domain to domain.uk just for example purposes and I don't wan't to expose the domain of my site just yet as its under development.

路线(在开发时出于测试目的制作一条路线:: any,通常在生产时会发布):

Routes (Made the one route ::any for testing purposes while developing, usually on production it would be post):

Route::group(['domain' => 'api.domain.uk', 'namespace' => 'Api'], function() {
    Route::group(['middleware' => ['cors'], 'prefix' => 'call'], function() {
        Route::get('/rooms/{id}/get-locked-status', 'ApiController@getRoomLockStatus');
        Route::any('/rooms/{id}/update-locked-status', 'ApiController@updateRoomLockStatus');
    });
});

错误:

XMLHttpRequest cannot load http://api.domain.uk/ajax/rooms/1/update-locked-status. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://ice.domain.uk' is therefore not allowed access. The response had HTTP status code 500.

中间件:

Middleware:

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', '*')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
            ->header('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With, Application');
    }
}

Ajax:

function toggleDoors(roomId) {
    $.ajax({
        url: 'http://api.domain.uk/ajax/rooms/' + roomId + '/update-locked-status',
        type: "POST",
        success: function(data) {
            alert(data);
        }
    });
}

ApiController:

ApiController:

<?php
namespace App\Http\Controllers\Api;

use Auth;
use App\User;
use App\Http\Controllers\Controller;
use Validator;
use Redirect;
use Illuminate\Http\Request;
use App\Database\Frontend\Other\Rooms;

class ApiController extends Controller
{
    public function getRoomLockStatus($id) {
        $room = Rooms::find($id);

        if ($room == null) {
            return response('bad request', 400);
        } 
        else {
            return $room->rp_locked;
        }
    }

    public function updateRoomLockStatus(Request $request, $id) {
        $room = Rooms::find($id);

        if ($room == null) {
            return response('bad request', 400);
        } 

        $room->rp_locked = $room->rp_locked == '1' ? '0' : '1';
        $room->save();

        $responseText = $room->rp_locked == '1' ?
            'Your doors have been locked.' : 'Your doors have been unlocked.';

        return response($responseText, 200);
    }
}

推荐答案

请参见 https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Methods/OPTIONS#Preflighted_requests_in_CORS

如果您在OPTIONS方法中遇到问题.

If your problem in OPTIONS method.

对于请求方法选项,内核:: $ routeMiddleware在Laravel 5.4中不起作用,请参见

Kernel::$routeMiddleware not working in Laravel 5.4 for request method OPTIONS, see https://github.com/laravel/framework/blob/v5.4.0/src/Illuminate/Routing/RouteCollection.php#L214. For use CORS middleware, enable it in Kernel::$middleware array. It is not good, but no other way.

例如,我将下一个中间件类用于SPA和API,请注意,它不是用于路由的中间件"cors"

For example, I use next middleware class for SPA and API, attention, it is not middleware 'cors' for routes

<?php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

/**
 * OptionsCorsResponse middleware - add CORS headers if request method OPTIONS
 */
class OptionsCorsResponse
{
    /**
     *
     * @param Request $request
     * @param Closure $next
     * @return Response
     */
    public function handle($request, Closure $next)
    {
        /* @var $response Response */
        $response = $next($request);
        if (!$request->isMethod('OPTIONS')) {
            return $response;
        }
        $allow = $response->headers->get('Allow'); // true list of allowed methods
        if (!$allow) {
            return $response;
        }
        $headers = [
            'Access-Control-Allow-Methods' => $allow,
            'Access-Control-Max-Age' => 3600,
            'Access-Control-Allow-Headers' => 'X-Requested-With, Origin, X-Csrftoken, Content-Type, Accept',
        ];
        return $response->withHeaders($headers);
    }
}

并在App \ Http \ Kernel中启用它

and enable it in App\Http\Kernel

protected $middleware = [
    // ...
    \App\Http\Middleware\OptionsCorsResponse::class,
];

起源'http://ice.领域 .因此,不允许使用"uk" 使用权.响应的HTTP状态码为500.

Origin 'http :// ice . domain . uk' is therefore not allowed access. The response had HTTP status code 500.

调试代码,因为它会生成一些异常.将任何REST客户端与OPTIONS方法一起使用.

Debug your code, because it generate some exception. Use any REST client with OPTIONS method.

这篇关于Laravel Cors(中间件不起作用)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆