Laravel - 响应 - Response
[ 字符串 & 数组响应 ]
最基本的响应就是从路由或控制器返回一串字符串。框架会自动将字符串转换为一个完整的 HTTP 响应
Route::get('response',function(){
return 'BulalalaPaBa';
});
[ 附加头信息至响应 ]
使用header('key' , 'value');
来添加需要的头信息
Route::get('response',function(){
return response('BulalalaPaBa', 200)
->header('Content-Type', 'text/plain');
});
也可以使用withHeader( [ 'key'=>'value' ] );
来添加
Route::get('response',function(){
return response('BulalalaPaBa', 200)
->withHeaders([
'x-title' => 'Title 1',
'y-title' => 'Title 2',
]);
});
用浏览器查看返回。
Cache-Control →no-cache, private
Connection →Keep-Alive
Content-Length →12
Content-Type →text/html; charset=UTF-8
Date →Mon, 05 Jun 2017 11:41:27 GMT
Keep-Alive →timeout=5, max=100
Server →Apache/2.4.23 (Win64) PHP/5.6.25
X-Powered-By →PHP/5.6.25
x-title →Title 1
y-title →Title 2
[ 重定向 ]
普通的跳转行为
Route::get('dashboard', function () {
return redirect('home/dashboard');
});
[ 重定向至命名路由 ]
return redirect()->route('login');
如果路由有参数,就如下
return redirect()->route('profile', ['id' => 1]);
[ 重定向至控制器 ]
return redirect()->action(
'UserController@profile', ['id' => 1]
);
[ JSON & JSONP 响应]
返回JSON请求
return response()->json([
'name' => 'Abigail',
'state' => 'CA'
]);
在json方法后面加上,withCallback 方法,就可以返回JSONP
return response()
->json(['name' => 'Abigail', 'state' => 'CA'])
->withCallback($request->input('callback'));
[ 文件下载 ]
download
方法可以用于生成强制让用户的浏览器下载指定路径文件的响应。download
方法接受文件名称作为方法的第二个参数,此名称为用户下载文件时看见的文件名称。最后,你可以传递一个包含 HTTP 头信息的数组作为第三个参数传入该方法:
return response()->download($pathToFile);
return response()->download($pathToFile, $name, $headers);