Angular $ http returns the header "no access control allow origin", but the jQuery $ .get query returns information

How can heck jQuery $ .get, $ .post and get the desired results, but angular can't $ http.get, $ http.post? Why doesn't the origin policy work for angular, but for jquery?

Laravel backend, angular front-end. I am considering using jQuery because this does not prevent client side CRUD actions.

I configured $ http and $ httpProvider ...

.run(function($http){
     $http.defaults.headers.common['Access-Control-Allow-Origin'] = "*";
     $http.defaults.headers.common['Access-Control-Allow-Methods'] = "GET, POST, PUT, DELETE, OPTIONS";
     $http.defaults.headers.common['Access-Control-Allow-Headers'] = "Authorization";
})
.config(function($httpProvider) {
    $httpProvider.defaults.useXDomain = true;
})

And laravel sends back the corresponding header ...

App::after(function($request, $response)
{
    // header('Access-Control-Allow-Origin', '*');
     $response->headers->set('Access-Control-Allow-Origin', '*');
});

So, the strange thing is angular $ http cannot get anything back from the server and causes this error:

XMLHttpRequest cannot load http://0.0.0.0:8000/api/test. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access. 

But jQuery $ .get and $ .post work correctly!

$.post('http://0.0.0.0:8000/api/test', function(resp){
    console.log(resp);
});

What am I doing wrong here?

+4
1
.config(['$httpProvider', function($httpProvider) {
        $httpProvider.defaults.useXDomain = true;
        delete $httpProvider.defaults.headers.common['X-Requested-With'];
    }
]);

useXDomain true . AJAX X-Requested-With, AJAX. , .

filters.php:

App::before(function($request)
{
    if (Request::getMethod() == "OPTIONS") {
        $headers = array(
        'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
        'Access-Control-Allow-Headers'=> 'X-Requested-With, content-type, Authorization',);
        return Response::make('', 200, $headers);
    }
});

+1

Source: https://habr.com/ru/post/1548386/


All Articles