Laravel中处理选项请求的原理是什么

  介绍

Laravel中处理选项请求的原理是什么,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

1。问题描述

Laravel处理<代码>选项>

假设我们请求的URL是http://localhost <代码>:8080/api/测试> 选项>

如果请求的URL不存在相关的其它方式(如<代码>得到或<代码> POST> 404 NOT FOUND>

如果存在相同的URL的请求,会返回一个状态码为<代码> 200>

举例而言,在路由文件<代码>路线/api.php> 选项> /api/测试> 200>

路线::获得(& # 39;/测试# 39;,,& # 39;TestController@test& # 39;); 

但同时通过分析可以发现,这个<代码>选项> 路由文件的生命周期内,至少该<代码> 请得到求所在路由文件<代码> api>

此时如果手动添加一个<代码>选项>

路线:获得(& # 39;/测试# 39;,,& # 39;TestController@test& # 39;);
  路线:选项(& # 39;/测试# 39;,,函数(Request  $请求),{
  ,,,return 响应(& # 39;abc # 39;);
  });

则至少会进入该<代码> 请得到求所在路由文件api <代码> 绑定的中间件,可以在相关<代码> 处理函数中捕获到这个请求。

2。分析源码

通过仔细查看Laravel的源码,发现了一些端倪。

在文件<代码>供应商/Laravel/框架/src/照明/路由/RouteCollection.php> 159> <>之前,,,,,,,,routes 美元;=,$ this→得到(请求→美元getMethod ());      ,,,,,,,//,,,will 阅读我方表示歉意if 还要find 我方表示歉意a  matching  route  for 却;能够current 请求   ,,,,,,,//,方法只If 可以,我方表示歉意,太好了,,还要just 我方表示歉意return  it  so  that  it 还要be 称   ,,,,,,,//,by ,消费者只Otherwise  will 我方表示歉意check  for  routes  with  another 动词。   ,,,,,,,route 美元;=,$ this→matchAgainstRoutes(路线美元,,请求);      ,,,,,,,if  (!, is_null(路线)美元),{   ,,,,,,,,,,,return 路线→美元绑定($请求);   ,,,,,,,}      ,,,,,,,//,If  no  route  was  found  will 你我方表示歉意check  If  a  matching  route  is  specified 通过   ,,,,,,,//,another  HTTP 动词只If  it  is  will 我方表示歉意need 用throw  a  MethodNotAllowed    ,,,,,,,//,inform 从而user  agent  of  which  HTTP  verb  it  should  use  for 却;能够路线。   ,,,,,,,others 美元;=,$ this→checkForAlternateVerbs($请求);      ,,,,,,,if  (count($),祝辞,0),{   ,,,,,,,,,,,return  $ this→getRouteForMethods(请求美元,,其他);   ,,,,,,,}      ,,,,,,,throw  new  NotFoundHttpException;

这里的逻辑是:

1。首先根据当前HTTP方法(GET/POST/PUT/?查找是否有匹配的路由,如果有(<代码>如果(!)is_null(路线)美元)条件成立),非常好,绑定后直接返回,继续此后的调用流程即可。

2。否则,根据<代码> $请求> count($)比;0)条件成立,则继续进入<代码> $ this→getRouteForMethods(请求,其他美元);方法;

3。否则抛出<代码> NotFoundHttpException> 404 NOT FOUND>

倘若走的是第<代码> 2步,则跳转文件的<代码> 234 行,可看到函数逻辑为:

<>之前,,,,protected  function  getRouteForMethods(请求,美元,array 美元方法)   ,,,{   ,,,,,,,if ($请求→方法(),==,& # 39;选项# 39;),{   ,,,,,,,,,,,return  (new 路线(& # 39;选项# 39;,,美元请求→路径(),,function  (), use (方法),{   ,,,,,,,,,,,,,,,return  new 响应(& # 39;& # 39;,,200年,[& # 39;允许# 39;,=祝辞,内爆(& # 39;& # 39;,,美元方法)));   ,,,,,,,,,,,}))→绑定($请求);   ,,,,,,,}      ,,,,,,,这个→美元methodNotAllowed($方法);   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null

Laravel中处理选项请求的原理是什么