laravel 跨域

andydaopeng / 2024-01-24 / 原文

laravel怎么设置跨域(两种方法)

在前后端分离的项目中,前端请求后端接口时可能会遇到跨域的问题。其中,一个典型的场景是:前端项目运行在 http://localhost:8080,而后端项目运行在 http://localhost:8000,这时候就需要设置跨域。

在 Laravel 中,要设置跨域可以采用以下两种方法。

1、中间件方式(已测试验证)

先创建一个中间件 CorsMiddleware

php artisan make:middleware CorsMiddleware

在 CorsMiddleware 中处理跨域:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class CorsMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        $origin = $request->header('Origin') ?: '*';

        header('Access-Control-Allow-Origin:' . $origin);
        header('Access-Control-Allow-Headers:Origin,Content-Type,Authorization');
        header('Access-Control-Allow-Methods:GET,POST,PUT,DELETE,OPTIONS');
        return $next($request);
    }
}

  该中间件会在 Http/Kernel.php 中的 $middleware 数组中注册:

    protected $middleware = [
       .....
        \App\Http\Middleware\CorsMiddleware::class,
    ];

这时候 Laravel 将在响应头中添加 Access-Control-Allow-Origin 等跨域相关的信息

2、Laravel-cors 扩展包

参考如下: (这种没有经过我测试验证)

 

视频转换处理(解决部分苹果手机的mp4视频在Edge浏览器无法播放的问题):

        //视频转换处理
        $oldPath = $messageInfo['content'];
        $filePath = '.'.ltrim($oldPath, '.');
        if(!file_exists($filePath)){
            return $this->showMsg(self::CODE_FAIL, self::MSG_PARAMS.':文件不存在');
        }
        $pathDir = dirname($filePath);//获取文件路径
        $fileName = getFileInfo($filePath, PATHINFO_FILENAME);
        $tmpNewFilePath = $pathDir.DIRECTORY_SEPARATOR.$fileName.'_tmp.mp4';//老文件临时重命名
        if(!rename($filePath, $tmpNewFilePath)){
            return $this->showMsg(self::CODE_FAIL, self::MSG_PARAMS.':无法重命名文件');
        }

        //$cmd="D:\xampp\ffmpeg\bin\ffmpeg.exe -i {$absoluteFilePath} -f image2 -ss 1 -t 0.001 -s 400*300 -vframes 1 {$videoThumImgPath}";
        $cmd=Common::getConfigValByEnv('FFMPEG_EXE_PATH', 'envs').' -i '.$tmpNewFilePath.' -y  -vcodec libx264 '.$filePath;
        @exec($cmd ,$output, $rtnVal);