0

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

2
  • You will need to handle origin requests in your API. You can use something like this: github.com/barryvdh/laravel-cors Commented Dec 7, 2016 at 1:52
  • you should always use google before asking question or at least Stack's search. You would get at least couple of answers without asking the same question as many, many people Commented Dec 7, 2016 at 12:39

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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;
    }
}

1 Comment

Thank you! I updated this middle-ware and used with my laravel 5.3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.