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

Foursquare API over Axios (Ajax) in Laravel not returning any data (500 internal server error)

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

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

ajax.js - Axios 调用:

//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);
    })

}

web.php - 路由

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

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

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client;

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 开发工具中的预览选项卡 这表示 businessLocation 索引未定义。

解决方法: 在 ajax.js 中,我删除了围绕我的实际名称和位置参数的 params{} 并停止了 500 内部错误。

因此:

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