In Laravel We must handle preflight requests by middleware or other ways. In my case, I did many but it never solved!
Here are what I tried,
Handle By Middleware
In this case, I did create a new middleware and put this code as handle method.
public function handle($request, Closure $next) {
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); }
and I added this to the $middleware array in kernel.php
Using laravel-cors
I used the laravel-cors library to handle cors but not works too
Adding cors handle codes in public/index.php
I added below codes at top of the public/index.php file,
if (isset($_SERVER["HTTP_ORIGIN"]) === true) {
$origin = $_SERVER["HTTP_ORIGIN"];
$allowed_origins = array(
"https://tapesh.io",
"http://tapesh.io",
"http://my.tapesh.io",
"http://panel.tapesh.io",
);
if (in_array($origin, $allowed_origins, true) === true) {
header('Access-Control-Allow-Origin: ' . $origin);
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: *');
header('Access-Control-Allow-Headers: Content-Type, X-Auth-Type, Origin');
}
if ($_SERVER["REQUEST_METHOD"] === "OPTIONS") {
exit; // OPTIONS request wants only the policy, we can stop here
}
}
Apache config
Also, I checked the apache error logs. the error was something like this,
[Sat Dec 07 07:35:36.678676 2018] [allowmethods:error] [pid 7902:tid
139855840466688] [client 84.417.45.0:4012] AH01623: client method
denied by server configuration: 'OPTIONS' to
/home/main/domains/example.com/private_html/api
I googled that and find out to handle this with apache I should add Require all granted to the Apache 2.4 config file of my domain. I did but not worked!
I must also say, in other projects, I used laravel-cors library and it solved mine.
I really confused about!
try adding the headers in your routes.php file:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
add more Allow-* headers if you want to. but of course, I suggest you use your code in 'Adding cors handle codes in public/index.php' section of your question in routes.php, because that's a safer bet
Related
I have an API Rest with Laravel 8.12 and a front-end with VueJS, locally I can connect to the API correctly, but when uploading everything to the server where the system will be, which has "Window Server 2012 R2" installed, when trying to consult the end points the API gives cors error, I tried installing laravel cors plugins, creating a middleware and nothing, it does not work always gives cors error.
Also try using the headers
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Allow: GET, POST, OPTIONS, PUT, DELETE");
I put these in the public/index.php and routes/api.php and it still gives the error.
I do not know if it is the server that is blocking due to some missing configuration, here I do not know completely how it would be done in the ISS.
How could I solve the cors error?
I am using a simple PHP backend and Angular frontend. I was having trouble with CORS. I have set proper headers and still faced CORS block. I tried a lot of things and noticed the following.
Since I expected a lot of PHP files I wanted uniformity among the responses. So, I created a PHP file called httpHelper.php and added a function that would set headers, response status code, and return the response.
The following is the httpHelper.php
<?php
function json_response($code = 200, $message = null)
{
header_remove();
http_response_code($code);
header('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, GET, POST");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
return "{ \"detail\":". $message."}";
}
The call to this function would be made from another PHP file that would be like,
echo json_response(200, json_encode(FALSE));
I was faced with the CORS block..
Access to XMLHttpRequest at
'http://localhost:8080/checkFeedbackStatus.php' from origin
'http://localhost:4200' has been blocked by CORS policy: Response to
preflight request doesn't pass access control check: It does not have
HTTP ok status.
But when the same httpHelper.php was coded with a constant status code, I have no issue.
<?php
function json_response($code = 200, $message = null)
{
header_remove();
http_response_code(200);
header('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, GET, POST");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
return "{ \"detail\":". $message."}";
}
I would like to know what I am missing, where things are getting messed up.
By the way, The request type was HTTP POST
It will not work until you use actual domain, it is currently against the CORS headers.
there may be several ways to make it work but i know only 2 of them.
Using Proxy in Xampp
Using Ngrok, this will provide you public domain to loopback on localhost.
If you are using xampp, you can edit httpd.conf and add a proxy at the end of the file and restart the apache service
ProxyPass /checkStatus http://localhost:8080/checkFeedbackStatus.php
ProxyPassReverse /checkStatus http://localhost:8080/checkFeedbackStatus.php
For Ngrok you can read the docs here
Once you setup ngrok, you can use any port to use ngrok as a public domain
ngrok http 8080
I have an issue with Laravel 5.3 CORS. I searched a lot on this issue, and found many recommending barryvdh for CORS. This however didn't work, and I found people mentioning that this could be caused by the use of tymondesigns jwt-auth module. Some suggests bypassing it by setting
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Authorization, Content-Type');
in the api.php file. This results in responses like:
Failed to load https://example.com/api/v1/members/1: Method PUT is not allowed by Access-Control-Allow-Methods in preflight response.
In attempt to resolve this issue I added
header('Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT');
to the above 2 lines. However this left me with a new issue:
PUT https://example.com/api/v1/members/1 403 (Forbidden)
Failed to load https://example.com/api/v1/members/1: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://example.com' is therefore not allowed access. The response had HTTP status code 403.
Any suggestions how to go about this?
If this is only happening on production, be sure to check your nginx configuration files. This is likely due to the following settings:
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";
Try commenting these out to see if that fixes the situation, then un-comment one by one, and make adjustments as necessary.
You can use three-way to solve this problem:
1) Use barrvay/laravel-cors
'supportsCredentials' => false,
'allowedOrigins' => ['http://localhost:4200'],
'allowedHeaders' => ['Content-Type','Accept','Authorization'],
'allowedMethods' => ['GET','POST','PUT', 'PATCH', 'OPTIONS', 'DELETE'],
'exposedHeaders' => ['Content-Disposition', 'x-total-count', 'x-filename'],
'maxAge' => 0,
'hosts' => ['*'],
2) Use Chrome Plugin (Moesif CORS) for localhost
3) Build a CORS middleware and putt all of cors header inside it
namespace App\Http\Middleware;
use Closure;
class Cors {
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}
}
I'm working on AngularJS and PHP application. When I try to run the index.html page, its throwing this error,
MLHttpRequest cannot load http://...... No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost' is therefore not allowed access.
The response had HTTP status code 500.
Working on LAMP.
I know I need to include the header files. But where should I include it? Should I include it in config.php where I had definded my database? If not then where??
You are missing CORS settings on your PHP headers, try adding following:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization, X-Request-With');
header('Access-Control-Allow-Credentials: true');
Set header:
header('Access-Control-Allow-Origin: http://example.com', false);
Now after starting to learn Angularjs and Laravel 4 I just love the way one can just set up a working development server with just one terminal command without having to set up virtualhosts or anything like that.
However...
I want to develop my frontend seperately so I can utilize the wonderful combination of yeoman and gruntjs and since I really can't do this if I put everything in laravel public folder (or at least I don't know how) this leaves me with the following situation:
I have a frontend grunt server at localhost:9000
And
I have a laravel 4 server at localhost:8000
This will of course mean that in order for Angularjs to talk with Laravel I have to allow CORS. In Apache this is easy: just adding Header add Access-Control-Allow-Origin "localhost:9000" to the directory part of httpd.conf allows this url to communicate with localhost.
Now where should I put this cors configuration when serving stuff via
artisan if its even possible?
Alright found the answer at least one working for me. It would seem I was approaching the problem from the wrong direction since I concentrated on Apache instead of Laravel itself.
In order to allow Cross Origin Response in a development environment via artisan the following code should be inserted in filters.php:
<?php
...
App::before(function($request)
{
if($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
$statusCode = 204;
$headers = [
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers' => 'Origin, Content-Type, Accept, Authorization, X-Requested-With',
'Access-Control-Allow-Credentials' => 'true'
];
return Response::make(null, $statusCode, $headers);
}
});
App::after(function($request, $response)
{
$response->headers->set('Access-Control-Allow-Origin', '*');
$response->headers->set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
$response->headers->set('Access-Control-Allow-Headers', 'Origin, Content-Type, Accept, Authorization, X-Requested-With');
$response->headers->set('Access-Control-Allow-Credentials', 'true');
return $response;
});
...
Also in case it is relevant I also added 'Access-Control-Allow-Origin' => '*' to Apache configation.
So now I can run my server environment in localhost:8000 and my frontend in localhost:9000 and they can talk to each other without problem.
I faced the same issue. You can find cors configuration in config/cors.php. By default all origins allowed only for api/* routes. You can add your own routes (e.g. oauth) to it like following:
'path' => ['api/*', 'oauth/*']