前后端分离开发中的laravel
在实际的开发当中,前端和后端的开发会同步进行
后台人员新建laravel项目,编写控制器和模型(视图),用于向前端同学提供数据,或者收集前端同学提供的数据
前端人员新建web或者android或者ios 等项目,用于获取后台人员提供的数据,渲染界面
1.新建项目
新建前端项目 news_client 和 后端laravel项目 news_server
文章列表展示
前端代码编写
在 news_client 项目中,新建 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<button class="btn btn-primary">添加文章</button>
<table>
<thead>
<tr>
<th>编号</th>
<th>标题</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</body>
</html>
<script>
loadData();
function loadData(){
$.ajax({
url:'http://127.0.0.1:8000/posts',
type:'get',
dataType:'json',
success:function(res){
console.log(res)
}
})
}
</script>
后端代码编写
创建路由
use Illuminate\Support\Facades\Route;
// 获取所有的文章信息
Route::get('/posts','PostController@index');
创建模型
php artisan make:model Post
创建控制器
php artisan make:controller PostController
编写 index 方法代码
class PostController extends Controller
{
// 获取所有文章信息
public function index(){
$res=Post::all();
return response()->json(['name'=>'姚宏波','age'=>18]);
}
}
此时请求,会产生跨域问题
跨域解决方案
利用 CORS 跨域资源共享
简单的说就是在被请求数据的网站中设置允许其他网站请求数据
创建中间件 CORS
php artisan make:middleware Cors
上面命令会在 App\Http\Middleware 目录下创建 Cors.php 文件,在 handle 方法中编写如下代码
public function handle($request, Closure $next)
{
$response = $next($request);
// 允许任何网站访问本网站的数据
$response->header('Access-Control-Allow-Origin', '*');
$response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie, Accept');
$response->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS');
$response->header('Access-Control-Allow-Credentials', 'false');
return $response;
}
注册中间件
在 app\http 的 kernel.php 文件中 的 $middleware 属性中,加入如下代码
重新请求即可实现跨域访问。