'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 :

  • spatia/laravel-cors module installed and tried
  • Added this in bootstrap/app.php:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: *');
header('Access-Control-Allow-Headers: *');
  • created CORS class file and added as middleware

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 1:[1]

I am using Laravel 8

check config/cors.php

change paths array to * ('paths' => ['*'])

Solution 2:[2]

For Laravel 8

In my case I added the origin that needs to access the resource.

// config/cors.php

// add a path to the resource here if you want it accessible to external origins
// for example no need to explicitly tell allowed origins
// what origins should gain access to api/* routes
'paths' => ['api/*', 'sanctum/csrf-cookie'],
'allowed_methods' => ['*'],

// explicitly tell which origins needs access to the resource
'allowed_origins' => ['*', 'https://mywebsite.com', 'http://mywebsite.com'],

// or use regex pattern, helpful if you want to grant
// access to origins with certain pattern (i.e. an origin under a subdomain etc.)
'allowed_origins_patterns' => ['/https?:\/\/mywebsite\.com\/?\z/'],

// no changes made below
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => false,

Also don't forget to run php artisan optimize in case you are caching the config.

Solution 3:[3]

Things you need to check if you are developing outlook addon :

  • Check whether you have included the domain name in manifest.xml ,in my case i need to include https://test.com to include in <AppDomain> tag.
  • Your domain should have ssl certificate .(ie) outlook allows you to request only through https .

And follow this answer as well : middleware to solve cors

Solution 4:[4]

This work for me:

php artisan make:middleware OwnCors

Code of the Middleware created:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class OwnCors
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        header("Access-Control-Allow-Origin: *");

        $headers = [
            'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE',
            'Access-Control-Allow-Headers' => 'Content-Type, X-Auth-Token, Origin, Authorization'
        ];
        if ($request->getMethod() == "OPTIONS") {
            return response('OK')
                ->withHeaders($headers);
        }

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

Add the middlware into your App\Http\Kernel.php

    protected $middleware = [
         \App\Http\Middleware\OwnCors::class,
         // Others middlewares
];

Solution 5:[5]

If you are using Laravel 7.0, it already has CORS functionality built in

Solution 6:[6]

Try this way in your laravel app:

php artisan serve --host YOUR_LOCAL_IP

YOUR_LOCAL_IP is your ip that can access with ifconfig command in linux and ipconfig in windows.

Finally you should request to YOUR_LOCAL_IP:PORT/api

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Praveen
Solution 2 Dale Ryan
Solution 3 Gomathimeena Subburayan
Solution 4 Gustavo Marquez
Solution 5 Syahnur Nizam
Solution 6 Abolfazl Mohajeri