gpt4 book ai didi

php - laravel artisan served 服务器在同一项目中请求 api.php 上的路由时挂起?

转载 作者:搜寻专家 更新时间:2023-10-31 20:57:32 25 4
gpt4 key购买 nike

我在 Routes 文件夹中的 api.php 如下所示:

<?php

use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::post('login', 'Api\User\LoginController@login');

web.php如下:

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/system/login', 'System\LoginController@index');

这是 System\LoginController.phpindex 方法的代码:

class LoginController extends Controller
{
use Requestable;

/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$response = $this->post('api/login',$request->all());
$responseArray = json_decode($response->getBody(), true);
session()->put('access_token',$responseArray['data']['token']);
return redirect()->to('/system/dashboard');

//
}

所以基本上,我在同一个项目中使用 api。项目文件夹位于 xampphtdocs 中。所以每当我打开并使用 Apache 服务器时,api 都会发送数据就好了。但是,如果我使用 php artisan serve 命令为项目提供服务,每次我尝试从 api 获取数据时,服务器都不会抛出任何错误,只是挂断并且不会即使经过很长时间也完全返回数据。我想这是服务器如何与 artisan serve 一起工作的问题。有人请帮我解决这个问题吗?

最佳答案

如果您仔细观察,这就是它的工作原理。

当您在浏览器中点击 /system/login(Web 请求)时,它会触发 php,它会寻找恰好是 System\LoginController@index 的正确路径。然后它运行 LoginController 中的索引函数。

现在它在运行中找到下面的行(API 请求)

$response = $this->post('api/login',$request->all());

所以在这一行中,相同的 php 实例(正在为网络请求提供服务)尝试调用自身!并且网络请求还没有完成。还要记住 PHP 的同步特性,它不会移动到下一行,直到当前行返回。

如果您注意到 here PHP 的内置服务器是一个单线程进程

The web server runs only one single-threaded process, so PHP applications will stall if a request is blocked.

它一次只能处理一个请求。因此,API 请求只是等待(在队列中)处理,因为 Web 请求尚未完成,Web 请求正在等待其刚刚进行的 API 调用的答案.This deadlock is the reason why everything gets hanged up.In case of production servers like Apache server this doesn't happen as Apache can spawn-off multiple processes/threads as and when needed 并将它们委托(delegate)给单独的 php 实例进行处理.

关于php - laravel artisan served 服务器在同一项目中请求 api.php 上的路由时挂起?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54120966/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com