laravel之http响应篇

这篇博客详细介绍了Laravel框架中的HTTP响应处理,包括基本响应、添加头信息、设置cookie,以及重定向响应的各种方式,如基本重定向、重定向到命名路由、控制器行为等。还提到了其他响应类型,如视图、JSON和文件下载响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、RESPONSE篇
   a.基本响应
     基本的响应是路由闭包或者控制器动作中返回一个字符串,除了返回字符串,当返回数组,Eloquent时,laravel会将数组转化为json响应
   b.返回相应对象
     Route::get('home',function(){
         //return response($content,$status)->header('key','value')
         return response('hello world',200)->header('Content-Type','text/plain');
     }):
   c.为响应添加头信息
     return response($content)
            ->header('Content-Type',$type)
            ->header('X-Header-one',$value)
            ->header('X-Header-two',$value);
     也可以使用withHeaders指定添加的信息头数组
     return response($content)->withHeaders([
                'Content-Type' => $type,
                'X-Header-one' => $value,
                'X-Header-two' => $value
             ]);
    d.为响应添加cookie
      return response($content)->header('Content-Type',$type)->cookie('name','value',$time);
      laravel生成的cookie都是经过加密和签名的,因此不能被客户端修改和读取,如果想要某些cookie不加密
      需要在App\Http\Middleware\EncryptCookies中间件的 $except 属性中添加cookie的名字
2、REDIRECT RESPONSE 重定向
   a.基本示例
    return redirect('home/dashboard');
    return back()->withInput();
   b.重定向到命名路由
    return redirect()->route('login');
    return redirect()->route('profile',['id'=>1]);//携带路由参数
    return redirect()->route('profile',$user);//通过eloquent模型填充参数
   c.重定向到控制器行为
    return redirect()->action('HomeController@index');
    return redirect()->action('HomeController@index',['id'=>1]);//携带路由参数
   d.重定向并利用闪存的session数据
     return redirect('dashboard')->with('status', 'Profile updated!');//重定向的时候讲数据闪到session数据
     在blade前端模板中
     @if (session('status'))
        <div class="alert alert-success">
            {{ session('status') }}
        </div>
     @endif
3、其他相应类型
   a.视图相应
     return response()
            ->view('hello', $data, 200)
            ->header('Content-Type', $type);
   b.json相应
     return response()->json([
        'name' => 'Abigail', //json方法自动添加json响应头信息,并使用json_encode方法
        'state' => 'CA'
     ]);
     如果创建jsonp响应,需使用json方法与withCallback方法配合使用
     return response()
            ->json(['name' => 'Abigail', 'state' => 'CA'])
            ->withCallback($request->input('callback'));
   c.文件下载
     return response()->download($pathToFile);
     return response()->download($pathToFile, $name, $headers);// $name是下载是所见的文件名
     return response()->download($pathToFile)->deleteFileAfterSend(true);
   d.文件响应
     return response()->file($pathToFile); //file 方法可以直接在浏览器中显示文件
     return response()->file($pathToFile, $headers);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值