Response响应(写Web页面时使用)
响应头部content-type: text/html;
namespace App\Http\Controllers; | |
use App\Http\Controllers\Controller; | |
use App\Models\User; | |
class UserController extends Controller | |
{ | |
/** | |
* 获取指定用户的简介 | |
* | |
* @param int $id | |
* @return \Illuminate\View\View | |
*/ | |
public function find($id) | |
{ | |
$user = User::find($id); | |
return response(['user' => $user]); | |
} | |
} |
JsonResponse响应(写Api时使用)
响应头部content-type: application/json;
namespace App\Http\Controllers; | |
use App\Http\Controllers\Controller; | |
use App\Models\User; | |
class UserController extends Controller | |
{ | |
/** | |
* 获取指定用户的简介 | |
* | |
* @param int $id | |
* @return \Illuminate\View\View | |
*/ | |
public function find($id) | |
{ | |
$user = User::find($id); | |
return response()->json(['user' => $user]); | |
} | |
} |
编写Api时合理选择响应类型的重要性
写Api的时候应该选择JsonResponse响应,不然响应头部就会错误(content-type: text/html;),这样可能会导致很多的问题。比如当token失效时,laravel的认证守卫如果识别到你的响应头部为content-type: text/html; 那它将会帮你做一个自动跳转到login页面,我们知道api是无法跳转的,所以这时候你客户端那里并能获取到http status为401的响应,就会对你系统造成影响