Laravel api CORS error when posting from js - laravel

I have made an API with Laravel and I am getting an error when I am trying to make a post. I don't know if I need to send the crsf from javascript or if I have made the cors middleware wrong.
When I make a get to the API I don't have any cors issue.
This is my middleware. It has been added on the kernel.php file.
class Cors{
public function handle($request, Closure $next) {
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers', 'Origin, Content-Type, X-Auth-Token, Authorization, X-Requested-With, x-xsrf-token, ip');
}
}
On javascritp I have added this: 'Content-Type': 'application/json' on the header.
And this is the error that it's giving to me
Access to XMLHttpRequest at 'http://localhost:8000/api/user/1/videos/1/newComment' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Thanks you a lot for your help.

Try adding this to the top of the index.php in the root of your project...
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
?>

Related

Method PUT is not allowed by Access-Control-Allow-Methods in preflight response vue-laravel App

I am new in vue. For ajax request I am using axios and for back-end I am using Laravel. Whenever I send a POST and GET request it's works fine. But while trying to send a PUT Request its showing Method PUT is not allowed by Access-Control-Allow-Methods in preflight response vue-laravel App. I had read lots of answer in Stackoverflow and github but none of them worked for me.
Here is the client side code:
axios.put('http://127.0.0.1:8000/api/photo/6', this.photo, { headers: getHeader() })
.then(response => {
console.log(response.data.message);
}).catch(err => {
this.errors = err.response.data.errors;
});
Here is CROSS middleware code:
//allowed client
//now only for localhost vue cli
$domains = ['http://localhost:8080'];
if(isset($request->server()['HTTP_ORIGIN'])){
$origin = $request->server()['HTTP_ORIGIN'];
if(in_array($origin, $domains)){
header('Access-Control-Allow-Origin: '.$origin);
header('Access-Control-Allow-Headers: Origin, Content-Type, Authorization');
}
}
return $next($request);
Try this in backend :
app/Http/Middleware/Cors.php
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE,
OPTIONS');
}
app/Http/Kernel.php $routedMiddleware array add
'cors' => \App\Http\Middleware\Cors::class,
Route/api.php
Route::group(['middleware' => 'cors'], function () {
Route::put('/v1/employees', 'Employees#store');
});
Particular GET, HEAD and POST HTTP requests do not trigger the CORS preflight OPTIONS check. They are called Simple Requests. They only send a subset of HTTP headers along. Any other additional header, like an Authorization header (think JWT authentication), will trigger a preflight OPTIONS request. The details on this can be found on https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
I think the easiest way for you to work with this, is to use the laravel-cors package on the backend (see https://github.com/barryvdh/laravel-cors).
While doing development, you can simply be very permissive by setting allowedOrigins, allowedHeaders and allowedMethods to *. Later on, during testing and subsequently production, you should tune it to be more strict. By that time you'll have a much better hang of CORS concepts, and then you can configure it fully to your needs.

Vuejs and Laravel Post Request CORS

I dont get it. I am struggling with this since hours
I am using Vue.js with Laravel and try to make a POST Request to an external API.
But i am always getting a CORS error on my Vue POST Request
methods: {
chargeCustomer(){
this.$http.post('/api/chargeCustomer', this.payment).then(function (response) {
console.log(response.data)
},function (response) {
console.log(response.data)
});
}
}
ERROR
MLHttpRequest cannot load
https://www.mollie.com/payscreen/select-method/JucpqJQses. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'https://payment.dev' is therefore not allowed
access.
I installed the Laravel CORS Package for my Backend and added the middleware to my route e.g
Route::group(['middleware' => 'cors'], function(){
Route::post('/api/chargeCustomer', 'Backend\PaymentController#chargeCustomer');
});
But i am still getting the error. I also tried to add the Vue Headers with
Vue.http.headers.common['Access-Control-Allow-Origin'] = '*';
Vue.http.headers.common['Access-Control-Request-Method'] = '*';
With the same result/error.
Could someone tell me what i am doing wrong?
You need to set up the CORS headers from the middleware. Maybe you need some extra setup?
Anyway, you can create your own middleware and set up the CORS headers in the handle() method like the following example:
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', 'http://yourfrontenddomain.com') // maybe put this into the .env file so you can change the URL in production.
->header('Access-Control-Allow-Methods', '*') // or specify `'GET, POST, PUT, DELETE'` etc as the second parameter if you want to restrict the methods that are allowed.
->header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Authorization') // or add your headers.
}
Add your custom middleware to the global $middleware array (under CheckForMaintenanceMode::class) in the Kernel.php class and you should be good to go.
Other way (without creating a new laravel middleware) is add these headers at the begining of your routes.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');
and add this before your interceptors on vue:
Vue.http.options.crossOrigin = true

Laravel 4.2 - Disabling Set-Cookie Header for OPTIONS responses

I have a stateless API built with Laravel. I use the following filter to prevent the Set-Cookie header from being sent back to the requester on all requests:
Route::filter('auth.firewall', function(){
Config::set('session.driver', 'array');
});
My API is called from a different sub-domain than the one it's hosted at and an OPTIONS request is sent from the client before any RESTful request. On the response to these OPTIONS requests, Laravel is still sending a Set-Cookie header.
How would I disable the Set-Cookie header for OPTIONS requests? I want to disable Set-Cookie for only the API and not the whole Laravel application since I have a site running off of the same Laravel app and using Larave's sessions capabilities.
This is what my header settings currently look like:
App::before(function(){
// Allow CORS requests
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization, X-Request-With, userToken, user_token');
header('Access-Control-Allow-Credentials: true');
});
I added a $request->getMethod() to the callback function registered with App:before. If the request was an OPTIONS request, I set the session driver to array.
App::before(function($request){
// Allow CORS requests
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization, X-Request-With, userToken, user_token');
header('Access-Control-Allow-Credentials: true');
if($request->getMethod() == 'OPTIONS'){
Config::set('session.driver', 'array');
}
});

OPTIONS request returns "No 'Access-Control-Allow-Origin' header" error during ajax POST to a different domain

I'm struggling with CORS issue. I make a request from js to a different domain, the method allows cross domain request and all works fine with GET but not with POST request. Looks like OPTIONS method is called before the POST and return standard error
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
return Response.ok().entity(c).header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS")
.header("Access-Control-Allow-Headers", "Content-Type, x-xsrf-token, X-Requested-With, Accept, Expires, Last-Modified, Cache-Control").build();
On the client side I use angularjs
$http.post(url, data).success(...)
But also tried with
$.ajax({type:'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}...})
the same result. what else can I do to fix POST request?
Add the below code to your Angular JS application config file
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];

HTTP OPTIONS error in Phil Sturgeon's Codeigniter Restserver and Backbone.js

My backbone.js application throwing an HTTP OPTIONS not found error when I try to save a model to my restful web service that's located on another host/URL.
Based on my research, I gathered from this post that :
a request would constantly send an OPTIONS http request header, and not trigger the POST request at all.
Apparently CORS with requests that will "cause side-effects on user data" will make your browser "preflight" the request with the OPTIONS request header to check for approval, before actually sending your intended HTTP request method.
I tried to get around this by:
Settting emulateHTTP in Backbone to true.
Backbone.emulateHTTP = true;
I also allowed allowed all CORS and CSRF options in the header.
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
The application crashed when the Backbone.emulateHTTP line of code was introduced.
Is there a way to respond to OPTIONS request in CodeIgniter RESTServer and are there any other alternatives to allow either disable this request from talking place?
I found this on Github as one solution. I am not sure if I should use it as it seems a bit outdated.
I encountered exactly the same problem. To solve it I have a MY_REST_Controller.php in core and all my REST API controllers use it as a base class. I simply added a constructor like this to handle OPTIONS requests.
function __construct() {
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");
$method = $_SERVER['REQUEST_METHOD'];
if($method == "OPTIONS") {
die();
}
parent::__construct();
}
This just checks if the request type is OPTIONS and if so just dies out which return a code 200 for the request.
You can also modify the $allowed_http_methods property in your subclass to exclude the options method. Previous versions of REST_controller did nothing with OPTIONS and adding this line seems to mimic that behavior:
protected $allowed_http_methods = array('get', 'delete', 'post', 'put');
I solved in this way:
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, x_requested_with");
if ( "OPTIONS" === $_SERVER['REQUEST_METHOD'] ) {
die();
}
Pay attention to add x_requested_with in Access-Control-Allow-Headers.

Resources