前后端分离开发中的laravel(跨域)

前后端分离开发中的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 属性中,加入如下代码

在这里插入图片描述

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值