跨域请求后端配置

原生

$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',
        ],
    ];
php
本作品采用《CC 协议》,转载必须注明作者和本文链接
welcome come back
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
未填写
文章
95
粉丝
24
喜欢
156
收藏
347
排名:323
访问:2.9 万
私信
所有博文
社区赞助商