我正在尝试测试Laravel API端点,并希望在代码中调用它。
$request = Request::create( $path, $method );
$response = Route::dispatch( $request );
此代码段适用于 GET,但我也需要能够设置 POST 调用。 将$method设置为 POST 也可以,但我找不到详细说明如何附加 post 数据的文档。
有什么建议吗?
正如您在评论中提到的,您可以使用$this->call()
但实际上您也可以使用当前的代码来做到这一点。如果你看一下Request::create()
函数的签名,你可以看到它把$parameters
作为第三个参数:
public static function create($uri, $method = 'GET', $parameters = array(), $cookies = array(), $files = array(), $server = array(), $content = null)
文档块说:The query (GET) or request (POST) parameters
因此,您只需将数据添加到Request::create()
$data = array('foo' => 'bar');
$request = Request::create( $path, $method, $data );
$response = Route::dispatch( $request );
我花了将近一天的时间试图让自己使用护照和 Angular 前端进行社交认证。
当我使用 Restlet API 客户端发出请求时,我总是得到成功的响应。Restlet 客户端请求
Restlet 客户端响应
但是,使用以下方法提出内部请求总是给我一个错误。
$request = Request::create(
'/oauth/token',
'POST',
[
'grant_type' => 'social',
'client_id' => 'your_oauth_client_id',
'client_secret' => 'your_oauth_client_secret',
'provider' => 'social_auth_provider', // e.g facebook, google
'access_token' => 'access_token', // access token issued by specified provider
]
);
$response = Route::dispatch($request);
$content = json_decode($response->getContent(), true);
if (! $response->isSuccessful()) {
return response()->json($content, 401);
}
return response()->json([
'content' => $content,
'access_token' => $content['access_token'],
'refresh_token' => $content['refresh_token'],
'token_type' => $content['token_type'],
'expires_at' => Carbon::parse(
$content['expires_in']
)->toDateTimeString()
]);
此特定错误:
{
error: "unsupported_grant_type",
error_description: "The authorization grant type is not supported by the
authorization server.",
hint: "Check that all required parameters have been provided",
message: "The authorization grant type is not supported by the authorization server."
}
我觉得这与表单数据在请求中的发送方式有关,因此在寻找在 laravel 中发出此类内部请求的正确方法时,我遇到了这个带有工作实现的示例项目:护照-社会-赠款-示例。
总之,这是如何做到这一点:
$proxy = Request::create(
'/oauth/token',
'POST',
[
'grant_type' => 'social',
'client_id' => 'your_oauth_client_id',
'client_secret' => 'your_oauth_client_secret',
'provider' => 'social_auth_provider', // e.g facebook, google
'access_token' => 'access_token', // access token issued by specified provider
]
);
return app()->handle($proxy);
希望这有帮助。