Skip to content
This repository has been archived by the owner on Feb 16, 2023. It is now read-only.

Laravel 5.0 Support #24

Closed
what4893 opened this issue Oct 11, 2014 · 35 comments
Closed

Laravel 5.0 Support #24

what4893 opened this issue Oct 11, 2014 · 35 comments

Comments

@what4893
Copy link

With the new middleware implementation in Laravel 5.0 this package no longer works.

@barryvdh
Copy link
Member

Bummer, will look when it's in beta.

@barryvdh
Copy link
Member

First try, can you check it out: 402de0f

You need to add the Middleware manually.

@grepollo
Copy link

grepollo commented Dec 2, 2014

Hi I tried your steps in setting up on Laravel 5 but no luck, see my configuration below:

return array(

'defaults' => array(
    'supportsCredentials' => false,
    'allowedOrigins' => array('*'),
    'allowedHeaders' => array('X-API-KEY', 'Origin', 'Language', 'Content-Type', 'Accept', 'Access-Control-Request-Method'),
    'allowedMethods' => array('POST', 'PUT', 'GET', 'DELETE'),
    'exposedHeaders' => array(),
    'maxAge' => 0,
    'hosts' => array(),
),

'paths' => array(
    'api/*' => array(
        'allowedOrigins' => array('*'),
        'allowedHeaders' => array('*'),
        'allowedMethods' => array('*'),
        'maxAge' => 3600,
    ),
    '*' => array(
        'allowedOrigins' => array('*'),
        'allowedHeaders' => array('X-API-KEY', 'Origin', 'Language', 'Content-Type', 'Accept', 'Access-Control-Request-Method'),
        'allowedMethods' => array('POST', 'PUT', 'GET', 'DELETE'),
        'maxAge' => 3600,
        'hosts' => array('api.*'),
    ),
),

);

Already added in Service provider and Middleware too.

Do you have a detail guide for Laravel 5? thanks.

@what4893
Copy link
Author

what4893 commented Dec 8, 2014

I have tested the updated code. It is working for GET/OPTION requests. However, when I try POST/PUT/DELETE requests I'm receiving a 302 Found response, and the request is never processed. Does that sound like something it should be doing or perhaps something I'm doing wrong?

EDIT: This was on my end. Everything appears to be working perfect. Thanks for the update.

@what4893
Copy link
Author

what4893 commented Dec 8, 2014

As a side note Laravel 5 no longer uses config:publish in Artisan, it uses publish:config, just wanted to point that out for anybody having trouble getting it setup until the documentation has been updated.

@MikeElghali
Copy link

Hi,

@what4893 There is no more publish:config too with latest Laravel 5 version and there is no config/packages too.

@barryvdh Any idea how i can publish your package?

Regards.

@etiennemarais
Copy link

Hi,

Please provide an example how the package config would get loaded into laravel 5 ConfigServiceProvider? I can't seem to get this right

@pfried
Copy link

pfried commented Jan 23, 2015

my experience is that the config in the config folder is not getting loaded (had some thougts why my rules do not work except on /api 😆 , i edited the config/config.php in the vendor folder which does what i expect.

@barryvdh
Copy link
Member

You have to load it yourself, using the config() helper

@pfried
Copy link

pfried commented Jan 23, 2015

I do not know where the config helper method is, if you referred to the artisan command, i guess that one is gone

@barryvdh
Copy link
Member

Not sure, something like this?

https://github.com/laravel/laravel/blob/develop/app/Providers/ConfigServiceProvider.php

public function register()
    {
        config([
            'laravel-cors' => [
                'defaults' => array(
                    'supportsCredentials' => false,
                    'allowedOrigins' => array(),
                    'allowedHeaders' => array(),
                    'allowedMethods' => array(),
                    'exposedHeaders' => array(),
                    'maxAge' => 0,
                    'hosts' => array(),
                ),
                'paths' => array(
                    'api/*' => array(
                        'allowedOrigins' => array('*'),
                        'allowedHeaders' => array('*'),
                        'allowedMethods' => array('*'),
                        'maxAge' => 3600,
                    ),
                    '*' => array(
                        'allowedOrigins' => array('*'),
                        'allowedHeaders' => array('Content-Type'),
                        'allowedMethods' => array('POST', 'PUT', 'GET', 'DELETE'),
                        'maxAge' => 3600,
                        'hosts' => array('api.*'),
                    ),
                ),
            ]
        ]);
    }

or app('config')->set('laravel-cors', require $pathToFile);

@pfried
Copy link

pfried commented Jan 23, 2015

perfect, thanks!

@billmn
Copy link

billmn commented Mar 7, 2015

I'm using this client code ( AngularJS + Restangular ) to make a request to a L5 app API:

Restangular.setBaseUrl('http://snapx-server.dev/api');

Restangular.all('user/login').post(credentials).then(function(response) {
    console.log(response);
},
function(error)
{
    console.error(error);
});

I've installed your package and added middleware manually to Kernel.php ... but I have this error:

XMLHttpRequest cannot load http://snapx-server.dev/api/user/login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://snapx-app.dev' is therefore not allowed access.

This is the configuration that I have used:

<?php

return array(

    /*
     |--------------------------------------------------------------------------
     | Laravel CORS Defaults
     |--------------------------------------------------------------------------
     |
     | The defaults are the default values applied to all the paths that match,
     | unless overridden in a specific URL configuration.
     | If you want them to apply to everything, you must define a path with *.
     |
     | allowedOrigins, allowedHeaders and allowedMethods can be set to array('*')
     | to accept any value, the allowed methods however have to be explicitly listed.
     |
     */
    'defaults' => array(
        'supportsCredentials' => true,
        'allowedOrigins' => array(),
        'allowedHeaders' => array(),
        'allowedMethods' => array(),
        'exposedHeaders' => array(),
        'maxAge' => 0,
        'hosts' => array(),
    ),

    'paths' => array(
        'api/*' => array(
            'allowedOrigins' => array('*'),
            'allowedHeaders' => array('*'),
            'allowedMethods' => array('*'),
            'maxAge' => 3600,
        ),
        '*' => array(
            'allowedOrigins' => array('*'),
            'allowedHeaders' => array('Content-Type'),
            'allowedMethods' => array('POST', 'PUT', 'GET', 'DELETE'),
            'maxAge' => 3600,
            'hosts' => array('api.*'),
        ),
    ),

);

Checking "Network" tab on Chrome DevTools I see this 2 requests:

OPTIONS

schermata 2015-03-07 alle 10 57 37

POST

schermata 2015-03-07 alle 10 57 52

I notice that in the 2° request, the response doesn't have the "Accept-*" headers ... is it right?
How can I solve this?

@cjmaio
Copy link

cjmaio commented Mar 10, 2015

Okay, so I'm going crazy trying to use this in Laravel 5, and I want to make sure I'm not doing anything wrong.

Using AngularJS to make the requests, if I make a request without any extra headers, this package works beautifully.

As soon as I add a header on (such as Authorization), Chrome / Safari / Firefox decide to do an OPTIONS request ahead of time. I get a 200 response, but without the Access-Control-Allow-Origin which makes the request fail.

Any way of getting around that? I've looked and looked and cannot find a solution for this.

@barryvdh
Copy link
Member

Did you enable supportsCredentials in the config and/or allowed the headers?

@cjmaio
Copy link

cjmaio commented Mar 10, 2015

Yes. This is the configuration I'm using to try and figure this out.

<?php

return array(
    'defaults' => array(
        'supportsCredentials' => true,
        'allowedOrigins'      => array('*'),
        'allowedHeaders'      => array('*'),
        'allowedMethods'      => array('POST', 'PUT', 'GET', 'DELETE', 'OPTIONS'),
        'exposedHeaders'      => array(),
        'maxAge'              => 3600,
        'hosts'               => array(),
    ),

);

@cjmaio
Copy link

cjmaio commented Mar 10, 2015

It seems that it fails at the OPTIONS preflight request no matter what extra header I add on. It's not limited to only Authorization.

@barryvdh
Copy link
Member

Hmm perhaps Laravel 5 change the way it handled OPTIONS request.

@cjmaio
Copy link

cjmaio commented Mar 10, 2015

It seems like if there is no body, the Access-Control-Allow-Origin does not come back in the OPTIONS request.

When I did this inside of the /public/index.php I was not getting the header in the OPTIONS response:

header('Access-Control-Allow-Origin: *');
die();

However, when I added some content, it showed up:

header('Access-Control-Allow-Origin: *');
echo 'hi';
die();

Thoughts?

@billmn
Copy link

billmn commented Mar 12, 2015

Any update?

@cjmaio
Copy link

cjmaio commented Mar 19, 2015

The way I got around it was this. It's not great, but it works. There has to be some form of text in the body. A blank body does not work. I put this inside of public/index.php before anything.

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    echo 'Hello';
}

Unless someone else has a better idea?

@rohan-deshpande
Copy link

I'm glad I'm not the only one running into this issue.

I can't get any response headers set from my API to my app. I'm using the example config posted above by @cjmaio with my app sitting on my.app and my api existing atapi.my.app.

Any GET or POST requests to api.my.app have the response headers set like this

Connection:keep-alive
Content-Length:574
Content-Type:text/html; charset=utf-8
Date:Fri, 27 Mar 2015 05:47:43 GMT
Server:nginx/1.6.2

I've set up my Kernel.php file like this

protected $middleware = [
    'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
    'Illuminate\Cookie\Middleware\EncryptCookies',
    'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
    'Illuminate\Session\Middleware\StartSession',
    'Illuminate\View\Middleware\ShareErrorsFromSession',
    'Barryvdh\Cors\Middleware\HandleCors',
];

FWIW if I go to the api routes directly in the browser I get the correct JSON responses printed into the window, so this is definitely a CORS issue, but I'm actually thinking Laravel might be the cause...maybe

Anyone got any further suggestions?

@rohan-deshpande
Copy link

Okay so, my issue was fixed when I changed my API request path and added a prefix for the domain. Not sure why this fixed the issue but it's working now.

However one thing is now the Content-Length header is no longer being set. Trying to figure out how to enable that now.

@barryvdh
Copy link
Member

barryvdh commented Apr 3, 2015

Can you guys checkout the 0.5.x@dev version? I removed the middleware (so should you from your Kernel) and added a before/handled filter. The handled filter should kick in, even on errors. (At least, errors after the beforefilter).

@thecodingwhale
Copy link

@barryvdh
I removed the middleware for 0.5.x@dev and it works smoothly on get requests but when I tried to send a post requests it failed suddenly. I'm using the default config/cors.php

@rohan-deshpande
Copy link

FWIW guys I got mine working totally fine on the old version which still has the middleware.

@thecodingwhale
Copy link

can you show how? i mean can you post your setup here?

@rohan-deshpande
Copy link

Yeah sure, I'm on a dev stack at the moment so all of these are just totally open for now, obviously in production the settings would change.

My app/config/cors.php file

<?php
    return array(
        'defaults' => array(
            'supportsCredentials' => true,
            'allowedOrigins' => array('*'),
            'allowedHeaders' => array('*'),
            'allowedMethods' => array('*'),
            'maxAge' => 3600,
            'hosts' => array()
        ),
        'paths' => array(),
    );

For some reason I commented out the entire vendor/barryvdh/laravel-cors/config/cors.php file. That's probably unnecessary.

My $middleware in my app/Http/Kernel.php file

protected $middleware = [
    'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
    'Illuminate\Cookie\Middleware\EncryptCookies',
    'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
    'Illuminate\Session\Middleware\StartSession',
    'Illuminate\View\Middleware\ShareErrorsFromSession',
    //'App\Http\Middleware\VerifyCsrfToken', //I'm not using cookies for authentication
    'Barryvdh\Cors\Middleware\HandleCors',
];

Then, and this was the real fixer, I prefixed my API underneath a route like this

Route::group(['domain' => "api.$TLD" , 'prefix' => $version], function()
{   
    /**
    *   stuff;
    */
}

Before I did this nothing worked. I just kept getting CORS errors. Hope this helps.

@thecodingwhale
Copy link

It works! Thanks! But, why we need to to comment out App\Http\Middleware\VerifyCsrfToken and remove App\Http\Middleware\VerifyCsrfToken? And also, what would be the proper config for production stack?

Again, thanks for helping out 👍

@rohan-deshpande
Copy link

I'm not sure if that middleware was causing issues with CORS...but I didn't need it personally as CSRF is more related to hijacking cookies that are used for Authentication - and I'm using JWTs so it's not really a concern for me. It depends on your project.

Again the production config would be totally based on your own use case, but basically just tightening down on allowed origins, the correct response headers etc.,

@Anatejms
Copy link

Anatejms commented Jun 2, 2015

I just downgrade to 0.4 and it works fine. Something is wrong with post request on 0.5

@caiotomazelli
Copy link

Can confim that downgrading to 0.4 fixed my CORS issues without further changes. I had problems even with GET requests on 0.5, more specifically with the following error message: "Request header field Authorization is not allowed by Access-Control-Allow-Headers."

For context's sake, I use Authorization header in order to do a Token-based authentication.

@barryvdh
Copy link
Member

barryvdh commented Jun 9, 2015

I've reverted the changes in 0.5, so 0.6.0 should be the same as 0.4, with L5.1 support.

@polyma
Copy link

polyma commented Jul 21, 2016

Hi, I've been having this problem specifically when trying to use CORS in a script tag in Internet Explorer (works fine in other browsers), laravel/framework#2962 (comment) this solution worked for me but I have no idea how/why.

@sokeno
Copy link

sokeno commented Feb 18, 2018

Hi guys , got a question, ive been doing a restfull app in laravel and im getting an error when i try to update .... PUT http://127.0.0.1:8000/api/task 405 (Method Not Allowed), can someone help?

public function update(Request $request, $id)
{
$currentUser = JWTAuth::parseToken()->authenticate();

$task = $currentUser->tasks()->find($id);
if(!$task)
    throw new NotFoundHttpException;

$task->fill($request->all());

if($task->save())
    return $this->response->noContent();
else
    return $this->response->error('could_not_update_task', 500);

}

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests