Test Laravel API on localhost cannot get response

Refresh

April 2019

Views

688 time

1

So have this laravel get product api that works if i called it from the browser as you can see from this image

enter image description here

here is the curl code chunk that tried to get this json response

$url = 'http://localhost:8000/api/products';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close($ch);
$result = json_decode($data,true);
echo $result;

but i cannot get anything in result, nothing to echo. I have one mockable api in https://demo0546443.mockable.io/products/getAllProducts that produce nearly the same json as my localhost api and it return response as it should have. please help

SOLUTION So after countless hours researching about this, it seems laravel needs to be accessed on static ip, not on localhost.

2 answers

0

It’s recommended to use a library like Guzzle though to make HTTP requests instead though.its very eazy to implement and work with

0

Rather than echo $result try return response()->json($data).

echo $result return Header application/html while json() return application/json hope this helps.