Laravel教程:对各种响应的处理示例
基本响应
每个请求都有响应。Laravel提供了几种不同的方法来返回响应。响应可以是来自路由或控制器发送。发送基本响应 - 如在下面示例代码所示出的简单字符串。该字符串将被自动转换为相应的HTTP响应。
示例
第1步 -将下面的代码添加到 app/Http/routes.php 文件。
app/Http/routes.php
Route::get('/basic_response', function () { return 'Hello World'; });
第2步 - 访问以下网址进行测试的基本响应。
http://localhost:8000/basic_response
第3步 - 输出结果如下图所示。


附加头
响应可以使用header()方法附加到头。我们还可以将一系列报头添加,如下示例代码所示。
return response($content,$status) ->header('Content-Type', $type) ->header('X-Header-One', 'Header Value') ->header('X-Header-Two', 'Header Value');
示例
第1步 -下面的代码添加到 app/Http/routes.php 文件。
app/Http/routes.php
Route::get('/header',function(){ return response("Hello", 200)->header('Content-Type', 'text/html'); });
第2步 - 访问以下网址进行测试的基本响应。
http://localhost:8000/header
第3步 - 输出结果如下图所示。


附加Cookies
withcookie()辅助方法用于附加 cookies。使用这个方法生成的 cookie 可以通过调用withcookie()方法响应实例附加。缺省情况下,通过Laravel 生成的所有cookie被加密和签名,使得它们不能被修改或由客户端读取。
示例
第1步 -下面的代码添加到 app/Http/routes.php 文件。
app/Http/routes.php
Route::get('/cookie',function(){ return response("Hello", 200)->header('Content-Type', 'text/html') ->withcookie('name','Virat Gandhi'); });
第2步 - 访问以下网址进行测试的基本响应。
http://localhost:8000/cookie
第3步 - 输出结果如下图所示。


JSON响应
JSON响应可以使用 json 方法发送。这种方法会自动设置Content-Type头为application/json。JSON的方法将数组自动转换成合适的JSON响应。
示例
第1步 -添加下面一行到文件 - app/Http/routes.php。
app/Http/routes.php
Route::get('json',function(){ return response()->json(['name' => 'Yiibai', 'state' => 'Hainan']); });
第2步 - 访问以下网址测试JSON响应。
http://localhost:8000/json
第3步 - 输出结果如下图所示。


THE END