跨域请求后端配置 
                                                    
                        
                    
                    
  
                    
                    原生
$origin = isset($_SERVER['HTTP_ORIGIN'])? $_SERVER['HTTP_ORIGIN'] : '';
$allowOrigin = [
    'https://xx.com',
    'https://xx2.com',
    'http://xx.com',
];
if (in_array($origin, $allowOrigin)) {
    header("Access-Control-Allow-Origin:".$origin);
}
header('Access-Control-Allow-Headers: X-Requested-With,X_Requested_With');
header('Content-type: text/json; charset=utf-8');
header('Access-Control-Allow-Methods: POST,GET');
Laravel
建立一个 middleware
<?php
namespace App\Http\Middleware;
use Closure;
class Cors
{
    public function handle($request, Closure $next){
        $response = $next($request);
        $response->withHeaders([
            'Access-Control-Allow-Origin' => '*',//填写允许跨域的origin
            'Access-Control-Allow-Methods'=> 'POST, GET',
            'Access-Control-Allow-Headers'=> '*',
        ]);
        return $response;
    }
}
然后在 App\Http\Kernel.php 中注册
protected $routeMiddleware = [
    ...
    'cors'     => \App\Http\Middleware\Cors::class,
];
在路由中使用中间件即可,例如:
//App\Http\Kernel.php
protected $middlewareGroups = [
        'web' => [
            ...
        ],
        'api' => [
            ...
            'cors',
        ],
    ];
                        
                        本作品采用《CC 协议》,转载必须注明作者和本文链接
          
          
          
                关于 LearnKu
              
                    
                    
                    
 
推荐文章: