Laravel server hangs whenever I try to request localhost:8000/any using guzzle

Viewed 4334

If I make any request to http://localhost:8000 or http://127.0.0.1:8000 it hangs on status pending. (Exactly as here https://github.com/guzzle/guzzle/issues/1857)

I was told that it isn't related to guzzle and that I should better ask about it here.

I stumbled upon this problem while following laravel.com/docs/5.4/passport

This is the code that hangs:

$response = $http->post('http://your-app.com/oauth/token', [
    'form_params' => [
        'grant_type' => 'authorization_code',
        'client_id' => 'client-id',
        'client_secret' => 'client-secret',
        'redirect_uri' => 'http://example.com/callback',
        'code' => $request->code,
    ],
]);

I tried making GET and POST request to working API routes (tested with postman) and it still hangs when calling the same routes using guzzle.

So is there a way to make requests to my own API while using php artisan serve?

4 Answers

Carl has a great solution to this. If you are looking for a quick fix to test your updates - you can get this done by opening up two command prompts. The first would be running php artisan serve (locally my default port is 8000 and you would be running your site on http://localhost:8000). The second would run php artisan serve --port 8001.

Then you would update your post request to:

$response = $http->post('http://localhost:8001/oauth/token', [
    'form_params' => [
        'grant_type' => 'authorization_code',
        'client_id' => 'client-id',
        'client_secret' => 'client-secret',
        'redirect_uri' => 'http://example.com/callback',
        'code' => $request->code,
    ],
]);

This should help during your testing until you are able to everything on server or a local virtual host.

/**
 * Login function
*/
public function login(Request $request) { 
    
    /* 
        Sample post object
        {
            "username": "test@gmail.com",
            "password": "test123"
        }
    */
    if (Auth::attempt(['email' => request('username'), 'password' => request('password')])) { 
       
        return $this->getToken($request);
    } 
    else { 
        return response()->json(['error'=>'Unauthorised'], 401); 
    } 
}

public function getToken(Request $request) {
    //Get client ID and client Secret
    $client = DB::table('oauth_clients')->where('password_client',1)->first();
    $request->request->add([
        "grant_type" => "password",
        "username" => $request->username,
        "password" => $request->password,
        "client_id"     => $client->id,
        "client_secret" => $client->secret,
    ]);
    // Post to "/oauth/token
    $tokenRequest = $request->create('/oauth/token','post');
    $instance = Route::dispatch($tokenRequest);
    //return token_type, expires_in, access_token, refresh_token
    return response()->json(json_decode($instance->getContent()));

}
Related