laravel 跨域
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');
//head r('Access-Control-Allow-Methods:GET,POST,PUT,DELETE,OPTIONS');
// return $next($request);
return $next($request)
->header('Access-Control-Allow-Origin', '*') // 请与你的实际情况相符
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers', '*');
} }
该中间件会在 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);
前端测试跨域请求Html 代码:
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<head>
<!-- 引入 jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
// 使用 jQuery.ajax() 发送请求
$.ajax({
// 替换为你的 API 地址
url: "http://lgzgw.com/api/article/detail",
method: "GET", // 请求方法 GET, POST...
data: { // 请求参数,需要在 POST 请求中使用
article_uuid:'1971ee5a046a4ac39e71918baef5fa84',
},
success: function(data) {
// 请求成功后执行的回调函数
console.log("返回数据:");
console.log(data);
alert('请求成功');
},
error: function(xhr, status, error) {
// 请求失败后执行的回调函数
console.log("请求出错:");
console.log("状态码:", xhr.status);
console.log("错误信息:", error);
alert('请求失败');
}
});
});
});
</script>
</head>
<body>
<button>发送跨域请求测试html_demo</button>
</body>
</html>
posted on 2024-01-24 11:03 andydaopeng 阅读(962) 评论(0) 收藏 举报
浙公网安备 33010602011771号