CruelIO
CruelIO

Reputation: 18624

CORS the easyway

I'm trying to 'put' data to my Laravel 5 server running on localhost from a webpage thats is also served localhost, but from other server software (nodejs). But im getting this error:

XMLHttpRequest cannot load http://localhost:8888/data/. Method PUT is not allowed by Access-Control-Allow-Methods.

The code that creates the put request is angularjs and looks like this:

 return $http.put("http://localhost:8888/data/", { obj1: a, obj2: b });

What is the simplest way to get around CORS? Security is no issue. Using the postman plug-in in chrome I'm able to send the put request.

Upvotes: 0

Views: 150

Answers (3)

M K
M K

Reputation: 9416

This is my laravel setup for cors.

I've created an http.php config file with this settings:

return [
    'cors' => [
        'origin' => '*',
        'methods' => 'OPTIONS, GET, POST, PUT, PATCH, DELETE',
        'headers' => 'X-Requested-With, Content-Type, Authentication-Token',
    ],
];

Run this code somewhere on application startup:

if ( ! App::runningInConsole()) {
    header('Access-Control-Allow-Origin: ' . Config::get('http.cors.origin'));
    header('Access-Control-Allow-Credentials: true'); // to be honest i've never used this option, but it looks like you'll need it

    // handle preflight requests
    App::before(function() {
        if (Request::getMethod() === 'OPTIONS') {
            return new Response('', 200, [
                'Access-Control-Allow-Methods' => Config::get('http.cors.methods'),
                'Access-Control-Allow-Headers' => Config::get('http.cors.headers'),
            ]);
        }
    });
}

Upvotes: 2

Felipe Skinner
Felipe Skinner

Reputation: 16626

It doesn't seem to be an Angular problem. You should try enabling CORS on the PHP with:

// Enable CORS 
// In production, replace * with http://yourdomain.com 
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Credentials: true');

Upvotes: 1

antoinestv
antoinestv

Reputation: 3306

Postman doesn't use CORS.

To enable CORS (in the client side) add : { withCredentials: true } in your put options :

 return $http.put("http://localhost:8888/data/", { obj1: a, obj2: b }, { withCredentials: true });

Note: Depending on your server application, you may enable them in the server side too.

Upvotes: 1

Related Questions