我在尝试使用cURL从我的其他网站检索数据时遇到困难
当我转到http://localhost/api/distributors
但是当我使用CLI并运行此命令curl -i --user test:1234 http://localhost/api/distributors
我无法连接到它,或者根本看不到任何json。
我不确定出了什么问题。 我很肯定我输入了正确的用户名和密码。
这是我的路线。
Route::get('/api/distributors', array('before' => 'auth.basic', 'uses'=>'DistributorController@api_index'));
它呼叫DistributorController
> api_index
这是我的api_index
函数
public function api_index()
{
$distributors = [];
foreach(Distributor::all() as $distributor)
{
$user = $distributor->user()->first();
$distributors[$distributor->id] = [
'user' => $user->toArray(),
'distributor' => $distributor->toArray(),
'contacts' => $distributor->contacts()->get()->toArray(),
'addresses' => $distributor->addresses()->get()->toArray()
];
}
$json_string = json_encode($distributors, JSON_PRETTY_PRINT);
return $json_string;
}
encoding
?看起来像这样:
<h1>Decode</h1>
<?php
$ch = curl_init("http://localhost/api/distributors");
curl_setopt($ch, CURLOPT_USERPWD, "test:1234");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$body = curl_exec($ch);
curl_close($ch);
?>
<?php $distributor = json_decode($body, TRUE); ?>
<!-- Test -->
<li><?php echo $distributor['distributor']['company_name']; ?></li>
尝试使用cURL进行连接时,我只有一个问题。
答案 0 :(得分:1)
routes.php
Route::group(array('prefix' => 'api', 'before' => 'auth.basic|api'), function(){
Route::resource('url', 'UrlController');
});
filters.php
添加auth.basic
// Auth Basic
Route::filter('auth.basic', function()
{
return Auth::basic("username");
});
添加api
过滤器
// API Route :: filter(&#39; api&#39;,function(){
$user = Auth::user();
if ($user){
// Let them in
}
else{
return Response::view('errors.404', array(), 404);
}
});
controller
函数并将其放在那里.. <?php
class UrlController extends \BaseController {
// public function index(){
// return Response::json(User::all());
// }
public function index()
{
$distributors = [];
foreach(Distributor::all() as $distributor)
{
$user = $distributor->user()->first();
$distributors[$distributor->id] = [
'user' => $user->toArray(),
'distributor' => $distributor->toArray(),
'contacts' => $distributor->contacts()->get()->toArray(),
'addresses' => $distributor->addresses()->get()->toArray()
];
}
return Response::json($distributors);
}
}