BetaDev
BetaDev

Reputation: 4674

Error: CORS in laravel/VueJS ajax request

I am getting cross origin problem while placing an AJAX request using VueJS to my Laravel Application. I Have written back end API with Laravel 5.3

Upvotes: 0

Views: 2000

Answers (2)

daninthemix
daninthemix

Reputation: 2570

This is the Cors Middleware I use:

namespace App\Http\Middleware;

use Closure;

class CorsMiddleware
{
    public function handle($request, Closure $next)
    {
        $headers = [
            'Access-Control-Allow-Origin'      => '*',
            'Access-Control-Allow-Methods'     => 'POST, GET, OPTIONS',
            'Access-Control-Allow-Credentials' => 'true',
            'Access-Control-Max-Age'           => '86400',
            'Access-Control-Allow-Headers'     => 'Content-Type, Authorization, X-Requested-With'
        ];

        if ($request->isMethod('OPTIONS')) {
            return response()->json('{"method":"OPTIONS"}', 200, $headers);
        }

        $response = $next($request);
        foreach($headers as $key => $value) {
            $response->header($key, $value);
        }

        return $response;
    }
}

Upvotes: 0

Saurabh
Saurabh

Reputation: 73589

If you are doing an XMLHttpRequest to a different domain than your page is on, your browser will block it as it usually allows a request in the same origin for security reasons. You need to do something different when you want to do a cross-domain request. A tutorial about how to achieve that is Using CORS.

When you are using postman they are not restricted by this policy. Quoted from Cross-Origin XMLHttpRequest:

Regular web pages can use the XMLHttpRequest object to send and receive data from remote servers, but they're limited by the same origin policy. Extensions aren't so limited. An extension can talk to remote servers outside of its origin, as long as it first requests cross-origin permissions.

To solve this, your external API server has to support cors request by setting following headers:

header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');

which can be done by laravel-cors as suggested in the comments.

Upvotes: 3

Related Questions