Laravel中的Foursquare API over Axios(Ajax)不返回任何数据(500内部服务器错误)



所以我试图在用户输入公司名称和位置名称后通过Foursquare API获取公司详细信息。 例如:"Huntrs"和"Brussel"应该通过Foursquare API获取此业务的详细信息,然后返回它们。

到目前为止,我正在尝试通过Axios在Laravel框架内进行Ajax调用。

ajax.js - Axios call:

//Ajax function to get company details when the getCompanyDetails() function is called on a btn click
function getCompanyDetails(){
//Get company name and location from form
let businessName =  document.querySelector('#businessName').innerHTML;
let businessLocation = document.querySelector('#businessLocation').innerHTML;
//Make the actual API GET request
axios.post('/getcompanydetails', {
params: {
businessName: businessName,
businessLocation: businessLocation 
}
})
.then(res => {
console.log(res);
console.log(res.data);
//Add response data to empty form fields
})
.catch(function (error) {
//Log request error in console, maybe also show onpage?
console.log(error);
})
}

网络.php - 路由

Route::post('/getcompanydetails', 'AjaxController@getCompanyDetails'); //Route for ajax call made from JS file ajax.js

AjaxController.php - 处理 Guzzle 对 API 的 ajax 调用请求的控制器

<?php
namespace AppHttpControllers;
use IlluminateHttpRequest;
use GuzzleHttpExceptionGuzzleException;
use GuzzleHttpClient;
class AjaxController extends Controller
{
//Make Foursquare API request with Guzzle!
public function getCompanyDetails() {
//Get params back from the Axios get Request
$params = json_decode(file_get_contents("php://input"),true);
$location = $params['businessLocation'];
$companyName = $params['businessName'];
//Setup actual Guzzle request
$client = new Client();
$result = $client->request('GET', 'https://api.foursquare.com/v2/venues/search', [
'query' => [
'client_id' => env('FOURSQUARE_CLIENT_ID'),
'client_secret' => env('FOURSQUARE_SECRET_ID'),
'v' => "20191009",
'near' => $location,
'query' => $companyName,
'limit' => 1
]
]);
//Return $result in JSON format to ajax.js
return response()->json($result);
}
}

正如 Saly 3301 所说,我必须检查网络选项卡: 网络 - Chrome 开发工具中的">预览"标签页 这表示业务位置索引未定义。

溶液: 在 ajax.js 中,我删除了我的实际名称和位置参数周围的参数{},这阻止了 500 内部错误。

因此:

axios.post('/getcompanydetails', {
businessName: businessName,
businessLocation: businessLocation
})

最新更新