Giter Club home page Giter Club logo

Comments (35)

barryvdh avatar barryvdh commented on May 11, 2024

Bummer, will look when it's in beta.

from laravel-cors.

barryvdh avatar barryvdh commented on May 11, 2024

First try, can you check it out: 402de0f

You need to add the Middleware manually.

from laravel-cors.

grepollo avatar grepollo commented on May 11, 2024

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.

from laravel-cors.

what4893 avatar what4893 commented on May 11, 2024

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.

from laravel-cors.

what4893 avatar what4893 commented on May 11, 2024

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.

from laravel-cors.

MikeElghali avatar MikeElghali commented on May 11, 2024

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.

from laravel-cors.

etiennemarais avatar etiennemarais commented on May 11, 2024

Hi,

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

from laravel-cors.

pfried avatar pfried commented on May 11, 2024

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.

from laravel-cors.

barryvdh avatar barryvdh commented on May 11, 2024

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

from laravel-cors.

pfried avatar pfried commented on May 11, 2024

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

from laravel-cors.

barryvdh avatar barryvdh commented on May 11, 2024

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);

from laravel-cors.

pfried avatar pfried commented on May 11, 2024

perfect, thanks!

from laravel-cors.

billmn avatar billmn commented on May 11, 2024

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?

from laravel-cors.

cjmaio avatar cjmaio commented on May 11, 2024

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.

from laravel-cors.

barryvdh avatar barryvdh commented on May 11, 2024

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

from laravel-cors.

cjmaio avatar cjmaio commented on May 11, 2024

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(),
    ),

);

from laravel-cors.

cjmaio avatar cjmaio commented on May 11, 2024

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.

from laravel-cors.

barryvdh avatar barryvdh commented on May 11, 2024

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

from laravel-cors.

cjmaio avatar cjmaio commented on May 11, 2024

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?

from laravel-cors.

billmn avatar billmn commented on May 11, 2024

Any update?

from laravel-cors.

cjmaio avatar cjmaio commented on May 11, 2024

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?

from laravel-cors.

rohan-deshpande avatar rohan-deshpande commented on May 11, 2024

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?

from laravel-cors.

rohan-deshpande avatar rohan-deshpande commented on May 11, 2024

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.

from laravel-cors.

barryvdh avatar barryvdh commented on May 11, 2024

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).

from laravel-cors.

thecodingwhale avatar thecodingwhale commented on May 11, 2024

@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

from laravel-cors.

rohan-deshpande avatar rohan-deshpande commented on May 11, 2024

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

from laravel-cors.

thecodingwhale avatar thecodingwhale commented on May 11, 2024

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

from laravel-cors.

rohan-deshpande avatar rohan-deshpande commented on May 11, 2024

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.

from laravel-cors.

thecodingwhale avatar thecodingwhale commented on May 11, 2024

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 👍

from laravel-cors.

rohan-deshpande avatar rohan-deshpande commented on May 11, 2024

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.,

from laravel-cors.

Anatejms avatar Anatejms commented on May 11, 2024

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

from laravel-cors.

caiotomazelli avatar caiotomazelli commented on May 11, 2024

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.

from laravel-cors.

barryvdh avatar barryvdh commented on May 11, 2024

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

from laravel-cors.

polyma avatar polyma commented on May 11, 2024

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.

from laravel-cors.

sokeno avatar sokeno commented on May 11, 2024

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);

}

from laravel-cors.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.