分离开发中的laravel
?
?
分離開發中的laravel:在實際的開發當中,前端和后端的開發會同步進行
新建項目
新建前端項目 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 屬性中,加入如下代碼
重新請求即可實現跨域訪問
總結
以上是生活随笔為你收集整理的分离开发中的laravel的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: f2fs学习笔记 - 1. f2fs概述
- 下一篇: MATLAB和C语言的区别