phplaraveloutlookcorsoutlook-addin

How to Solve CORS error in accessing laravel routes


Im very new to laravel applications.What im trying to do is developing an outlook web addon that uses the API written in laravel . The problem here is ,it produces the CORS error while accessing API's through outlook mail.

Error :

Access to XMLHttpRequest at 'https://test.com/api/test' from origin 'https://localhost:44377' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

What i have tried so far :

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: *');
header('Access-Control-Allow-Headers: *');

And finally end up with the same error.What should I do ?

Edit :

Why it automatically redirect the request to https instead of http .Where it went wrong ? The request url should be http://test.com/api/test ,not https://test.com/api/test

Thanks in advance !


Solution

  • I had the same problem, solved it by Middleware

    Define your custom middleware

    //App\Http\Middleware;
    
    public function handle($request, Closure $next)
    {
        return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', '*')
            ->header('Access-Control-Allow-Credentials', true)
            ->header('Access-Control-Allow-Headers', 'X-Requested-With,Content-Type,X-Token-Auth,Authorization')
            ->header('Accept', 'application/json');
    }
    

    Than just register yours Middleware, local (for specific route/routes) or global.

    How to register Middleware

    Notice! Some old brovsers do not support '*' logic