fruitcake / laravel-cors

Adds CORS (Cross-Origin Resource Sharing) headers support in your Laravel application
MIT License
6.27k stars 616 forks source link

No Access-Control-Allow-Origin header is present on the requested resource. #471

Open Suryadeep-bhujel opened 4 years ago

Suryadeep-bhujel commented 4 years ago

I am using Ubuntu 18.04 Operating system and working on Laravel Version 6.

I am working on api's where I wanted to cross site access. I am using Fruitcake/laravel-cors from laravel version 5.7 and it was working fine. Now I have issue on the Laravel version 6 .

I have installed the package as per given instructions. image

composer require fruitcake/laravel-cors

protected $middleware = [ \Fruitcake\Cors\HandleCors::class, // ... ]; image

*'paths' => ['api/'],** image image

php artisan vendor:publish --tag="cors"

My api.php file includes Route::group(['prefix' => 'v1'], function () { Route::post('/wtag', 'HomeController@UpdateMeta'); }); image image

Then, I updated my project as follow php artisan cache:clear php artisan config:clear composer dump-autoload

but still I am getting issue
image

I reinstalled the package for multiple times but still not getting solved.

Thank you

barryvdh commented 4 years ago

Can you move the middleware to the top?

Suryadeep-bhujel commented 4 years ago

Can you move the middleware to the top? image

Yes I moved it to the top, but still getting same error image

Krisell commented 4 years ago

Does the request actually work if you send it from the same domain as the api, or use postman?

paulocastellano commented 4 years ago

I have the same problem and API is working perfectly with Postman:

Screenshot from 2020-06-14 15-30-31

barryvdh commented 4 years ago

Please create your own issue please and add the config and postman response headers. V2 should include the control headers when possible. Also try adding your Origin header to the request.

paulocastellano commented 4 years ago

@barryvdh ok, I will create.

cvalenzuelab1982 commented 4 years ago

Hello, I have the same problem, and I cannot find the solution, I followed the steps on the page to install and update at the same time, here I made them.

1.- image

2.- image

3.- image

4.-and this is where I send my routes, with postman it responds without problems, in the routes I use "login" which is POST type, is this route ok to use with CORS?

image

I HOPE YOU CAN HELP ME PLS XD

ah add... image

barryvdh commented 4 years ago

Are those the api routes?

cvalenzuelab1982 commented 4 years ago

Thank you for answering, that's all for now.

cvalenzuelab1982 commented 4 years ago

Thanks for answering, that's all for now, I followed it as it is in the documentation, it could be that there is a bug??

paulocastellano commented 4 years ago

Thanks for answering, that's all for now, I followed it as it is in the documentation, it could be that there is a bug??

Certainly, the package has a bug, because there are many related problems here and in the laravel github on this subject.

Momentarily, I created my own middleware to add cors to my routes, while this bug is not identified and fixed.

barryvdh commented 4 years ago

Yeah you get that error when anything is wrong so ALL the errors are exactly the same. It could be that there is a bug but as long as I can't recreate it, it's kinda hard. So if you could please just open your own issue and follow the instructions.

barryvdh commented 4 years ago

It would help if you could see if the actual CORS middleware is ran, and what happens on the different places in the app.

cvalenzuelab1982 commented 4 years ago

Thanks for replying, I knew it haha, I had to make my own middleware cors too and it worked. It's a shame :(

cvalenzuelab1982 commented 4 years ago

I know I'm getting off the topic, but is there a way that when I receive a request, Laravel will return it with the headers it received? Tyyy

barryvdh commented 4 years ago

I'm not saying there is a bug though, just that I can't rule it out.

allaniftrue commented 4 years ago

Experiencing the same error.

image

image

image

andregarcia013 commented 4 years ago

Do not use this plugin, and make your own Middleware, I put in the General Middlewares and API middlewares

<?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)
    {
        header("Access-Control-Allow-Origin: *");
        //ALLOW OPTIONS METHOD
        $headers = [
            'Access-Control-Allow-Methods' => 'POST,GET,OPTIONS,PUT,DELETE',
            'Access-Control-Allow-Headers' => 'Content-Type, X-Auth-Token, Origin, Authorization',
        ];
        if ($request->getMethod() == "OPTIONS"){
            //The client-side application can set only headers allowed in Access-Control-Allow-Headers
            return response()->json('OK',200,$headers);
        }
        $response = $next($request);
        foreach ($headers as $key => $value) {
            $response->header($key, $value);
        }
        return $response;

    }
}
michaelkorshun commented 4 years ago

Noticed a problem, created a hidden form js and sent data, no problem with cors

Content-Type: multipart/form-data - work Content-Type: application/x-www-form-urlencoded - does not work

UPDATE: Sorry, there was a conflict with the library ZipStream.

M-Abdullahi commented 4 years ago

Screenshot from 2020-07-07 12-16-49 Hi. I am also experiencing the same issue. Screenshot from 2020-07-07 12-12-45 Screenshot from 2020-07-07 12-12-56 Screenshot from 2020-07-07 12-13-26

cimd commented 4 years ago

Same issue here. It was working fine on the previous 0.* version but it's failing now on the new 2.0 version of the repo.

davidquon commented 4 years ago

In case it helps others https://github.com/fruitcake/laravel-cors/issues/477#issuecomment-664709886. I'm using the 2.0 version on the server.

davidquon commented 4 years ago

Looks like there is another solution too (at least for my use case) setting supports_credentials to true. https://github.com/fruitcake/laravel-cors/issues/477#issuecomment-665166972

allaniftrue commented 4 years ago

mine was fixed. The issue was an error that causes the cors

DominiqueFERET commented 4 years ago

I have the same problem with AXIOS in a vuejs application using Laravel Sanctum authentication having a different domain name than the LARAVEL api. Laravel v7.25 and fruitcake/laravel-cors v2.01

I have the problem ONLY if the request sends data in JSON. In Formdata, it works well.

It also works, if you serialize data before sending with JSON.stringify()... (Content type is no longer application/json in this case, but application/x-www-form-urlencoded).

But laravel Request can't check the presence of JSON fields if you send data with a different content type of application/json. => so it's related to the fact that "Content-Type: application/json;charset=UTF-8" doesn't seem to be allowed.

However, like the other people here, I have the standard configuration file with 'allowed_headers' => ['*'], 'supports_credentials' => true etc...

Hoping that this might lead to some kind of solution...

Krisell commented 4 years ago

@DominiqueFERET

The content type of application/json triggers a preflight request (an OPTIONS) whereas application/x-www-form-urlencoded does not. Are you absolutely sure that the form-data requests are returned with the correct CORS headers, or have you only verified that the data is saved (CORS does not prevent the server from acting on the request, only the client from reading the response)? If you are sure, the difference must be a setting in your hosting provider. Some hosting providers have a CORS setting in the adminpanel and they might handle OPTIONS requests for you. If you use Cloudflare, there might be a setting there.

For instance, in the case of Azure, it's optional to let Azure handle the CORS headers (and full OPTIONS requests) or let it be handled by the application.

You can read more about the differences of application/json and application/x-www-form-urlencoded here: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

DominiqueFERET commented 4 years ago

I've solved my problem. In my case, it's "trustedproxy" middleware that's responsible for the bug.

=> You shouldn't put '*' in 'proxies'.

=> The transaction is functioning normally.

I hope this helps someone. It took me six hours to find a solution.

DominiqueFERET commented 4 years ago

@DominiqueFERET

The content type of application/json triggers a preflight request (an OPTIONS) whereas application/x-www-form-urlencoded does not. Are you absolutely sure that the form-data requests are returned with the correct CORS headers, or have you only verified that the data is saved (CORS does not prevent the server from acting on the request, only the client from reading the response)? If you are sure, the difference must be a setting in your hosting provider. Some hosting providers have a CORS setting in the adminpanel and they might handle OPTIONS requests for you. If you use Cloudflare, there might be a setting there.

For instance, in the case of Azure, it's optional to let Azure handle the CORS headers (and full OPTIONS requests) or let it be handled by the application.

You can read more about the differences of application/json and application/x-www-form-urlencoded here: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

Thank you for your answers. You're right. When I sent the transaction with content type 'application/x-wwww-form-urlencoded' I didn't have the CORS bug anymore but a 422 error caused by the Laravel request in charge of controlling the presence of such and such fields. But by disabling this request, I found the CORS error.

In my case, the fontend vueJS and the api Laravel are on the same network. During my search for a solution, I read a lot of posts about different possibilities (switch to fruitcake/laravel-cors v2, put '*' in 'proxies' in trustedproxy configuration, and a lot of other things). So I followed all these recommendations. Except that the one about 'proxies' was not wise. So I recommend putting this in trustedproxy instead: 'proxies' => env('PROXY', null),

Now, with v2 of fruitcake/laravel-cors, Content Type: "application/json" and laravel rules in Request to validate fields, everything work perfectly. Thank you for your attention.

barryvdh commented 4 years ago

Huh so is the proxy a common thing for all of you?

wagnermengue commented 4 years ago

I'm using axios from react and get same error:

Screen Shot 2020-08-15 at 09 45 56

GET works, POST not. But requests from postman to same host work.

awwit commented 4 years ago

@wagnermengue I had the same problem, it turned out to be an error in the my code. In the logs, it became clear to me that the request falls with an error, so it does not reach the filling of the CORS headers

KieronWiltshire commented 4 years ago

Huh so is the proxy a common thing for all of you?

I would assume this would need to be considering how Laravel Vapor works.

celorodovalho commented 3 years ago

I tried all the suggestions above, anything works for me. The only "weird" suggestion that worked, was to put this on routes/api.php

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

But I know this is a terrible solution, and would like to find a better and fancy solution.

I tried all the suggestions of @DominiqueFERET and, I tried to create a Cors middleware as well. Anything works.

download1 download2 Screenshot from 2020-10-18 20-29-24 Screenshot from 2020-10-18 20-29-48 Screenshot from 2020-10-18 20-30-19

Help?

barryvdh commented 3 years ago

Does this PR solve the issues with a proxy? https://github.com/asm89/stack-cors/pull/84

volpacchiotto commented 3 years ago

Do not use this plugin, and make your own Middleware, I put in the General Middlewares and API middlewares

namespace App\Http\Middleware; use Closure; class CORS { public function handle($request, Closure $next) { header("Access-Control-Allow-Origin: *"); $headers = [ 'Access-Control-Allow-Methods' => 'POST,GET,OPTIONS,PUT,DELETE', 'Access-Control-Allow-Headers' => 'Content-Type, X-Auth-Token, Origin, Authorization', ]; if ($request->getMethod() == "OPTIONS"){ return response()->json('OK',200,$headers); } $response = $next($request); foreach ($headers as $key => $value) { $response->header($key, $value); } return $response; } }

your class redirects to login page if metod is POST

mostafaebrahimi commented 3 years ago

I can not say my answer is correct exactly or not - But sometimes this problem happens when when something is wrong with code and that code is returning some exceptions- this causes to return the CORS error except that api error @barryvdh

KieronWiltshire commented 3 years ago

This also happens when you dd which is something I didn’t realise for a while.

barryvdh commented 3 years ago

Yeah see the common issues here: https://github.com/fruitcake/laravel-cors#common-problems

mpalencia commented 3 years ago

For those who are using sanctum

Try to enable the withCredentials option on your application's Frontend whenever you have a HTTP requests.. you need to adjust you Vue, Angular or React

gaffarmalik commented 2 years ago

I was also experiencing similar issues and I was initially confused why laravel-cors didn't work. I later discovered that the frontend needs to specify the 'Accept' header to inform Laravel of the accepted format. The validation handlers would cause a CORS error since by default, it would return response in a format different from the regular 'application/json'. So don't forget to add 'Accept':'application/json' in fetch headers based on your requirements.

osbre commented 2 years ago

I found this note on next-example-backend example:

Note: Currently, for this example, we recommend using localhost during local development to avoid "Same-Origin" issues.

I think it might solve some of the problems that people have here.