前后端分离开发中的laravel实例1

1.前后端分离开发中的laravel

在实际的开发当中,前端和后端的开发会同步进行

后台人员新建laravel项目,编写控制器和模型(视图),用于向前端同学提供数据,或者收集前端同学提供的数据

前端人员新建web或者android或者ios等项目,用于获取后台人员提供的数据,渲染界面

前端和后端程序之前使用ajax的方式交互数据

1.1新建项目

新建一个前端目录:posts_client
然后在命令行输入

composer create-project --prefer-dist laravel/larave/  news_server

下载laravel框架

1.2文章列表展示

1.2.1前端代码编写

在posts_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>
1.2.2后端代码编写

创建路由

use Illuminate\Support\Facades\Route; //引入文件
// 获取所有的文章信息
Route::get('/posts','PostController@index');

创建模型
在命令行输入

 php artisan make:model Post

创建控制器

 php artisan make:controller PostController

编写index方法代码
在创建的控制器中写一个方法

// 获取所有文章信息
    public function index(){
        $res=Post::all();
        return response()->json(['name'=>'姚宏波','age'=>18]);
    }

用于展示文章信息
这个时候,会产生跨域问题
跨域问题解决方案
利用 CORS 跨域资源共享

简单的说就是在被请求数据的网站中设置允许其他网站请求数据

创建中间件 CORS
可以在终端写入

 php artisan make:middleware Cors

上面的命令会在App\Http\Middleware目录下创建Cors.phpw摁键,在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 属性中,加入如下代码

//加入允许跨域访问的中间件
  \App\Http\Middleware\Cors::class

重新请求即可实现跨域访问

cors解决跨域可上百度查询。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值