angularjs 和 laravel 分别是当前框架里比较流行的框架,一个是前端js框架,一个是后端PHP框架。 国内的盆友都对先后端分离极其的热衷,这里我就和你们说说我用angularjs 和 laravel 搭建先后端分离框架的一个总体过程。php
laravel 框架里包含了前端渲染的功能,因此整合的过程当中。咱们要摒弃laravel 的渲染模板,laravel只提供纯粹的接口功能。css
angularjs 框架消费接口,并实现显示逻辑,页面跳转等前端功能。html
路由的各类问题,咱们从nginx的配置文件入手。前端
环境: ubuntu16.04 angular2.0 laravel5.2 nginx1.10nginx
下载安装laravel ,咱们这里用laravel 5.2版本的,能够从github下载。laravel
git clone https://github.com/laravel/laravel.git cd laravel composer install chmod -R 777 ./storage ./bootstrap/cache
laravel安装过程参考http://www.golaravel.com/laravel/docs/5.1/git
下载安装angularjs,教程中使用的是angular2.0 版本angularjs
git clone https://github.com/angular/angular.git
安装 nginx : 略;github
文件整合: 将angularjs 文件加放到 laravel 的public目录下,并重命名为views。 这个views就是咱们前端的开发目录。json
mv ./angular ./laravel/public/views
其实这个views也能够直接放在laravel的根目录,即跟app文件夹同一级,只不过是后面nginx写的路径不同而已。
laravel路由部分:laravel 只作接口路由,页面跳转和静态页面的请求一概找前端去。 因此这里路由只有这样配置就能够。
Route::get('/',function(){ //跳转到前端登陆的界面 return redirect('pages/login.html'); } ); //相应的接口路由 Route::get('/auth/login', 'Auth\AuthController@postLogin'); Route::get('/auth/logout', 'Auth\AuthController@getLogout'); //coding.. 其余路由
angular 目录结构:
public ├── index.php └── views ├── assets ├── bower_components // angular引用js脚本目录 ├── css │ └── style.css //自定义css目录 ├── data │ └── time.json ├── index │ ├── index.html ├── pages │ ├── blank.html │ ├── grid.html │ ├── index.html │ ├── login.html │ └── typography.html └── scripts ├── app.js ├── controllers └── services
配置nginx.conf 解决请求走前端仍是走后端问题。
这里咱们说一下这个问题,就是若是nginx.conf不作区分,那么先后端的请求所有都会去找后端去了,这样先后端就没分离了。
具体实现原理是这样的:咱们观察到views目录下有几个固定的文件夹, 一个bower_components放的引用文件,assets放的自定义开发的组件,css放的自定义的css文件,data放的固定数据,index放的前端主文件。 pages放的前端未渲染的页面,script 放的angular控制器等文件。当请求的uri头是这这几个目录名,那就让请求跑到angular目录来找。
nginx配置以下(这里我只贴出server部分的配置了):
server { listen 8080; server_name 0.0.0.0; #charset koi8-r; #access_log logs/host.access.log main; location ~ ^/(bower_components|css|data|scripts|pages){ root path/to/angular-laravel/public/views; index index.html; } location / { root path/to/angular-laravel/public; index index.php index.html index.htm; try_files $uri $uri/ /index.php?$query_string; #for laravel if (!-e $request_filename) { rewrite .* /index.php last; } } # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } # proxy the PHP scripts to Apache listening on 127.0.0.1:80 # #location ~ \.php$ { # proxy_pass http://127.0.0.1; #} # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 # location ~ \.php$ { root path/to/angular-laravel/public; fastcgi_pass localhost:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } # deny access to .htaccess files, if Apache's document root # concurs with nginx's one # #location ~ /\.ht { # deny all; #} }
这里就解决了请求是访问前端目录仍是走后端路由的问题了。