0

Quiero consultar un API desde mi controlador de Laravel,

$json = '[{"Identidad":"yes","DetailOpe":[]}]';

cualquiera

$json =n '[{"Identidad":"yes","DetailOpe":[{"IdClient":"0101425098","Assignor":"ICESA_COBRANZA","Operación":"105806003794060","Nombres":" RODRIGUEZ MORALES ANA OTILIA","Dayslate":"1294","Producto":"MOTO","Canal":"ALMACENES ORVE","Agencia":"ORVE TUMBACO","Pago":"1489.43"},{ " IdCliente":"0101425098","Assignor":"ICESA_COBRANZA","Operación":"105806004550710","Nombres":"RODRIGUEZ MORALES ANA OTILIA","Dayslate":"1491","Producto":"LED" , "Canal":"ORVE ALMACENES","Agencia":"ORVE TUMBACO","Pago":"809.26"}]}]';

mi ruta/vista en la ruta routes\web.php

Route::post('consultaSaldoIcesa', 'CollectionController@consultaSaldoIcesa');

mi controlador, en la ruta app\Http\Controllers\CollectionController.php

public function consultaSaldoIcesa(Request $request)
     {
$rules = array(
'cedula' => 'required',
);
$cedula = $request->cedula;
// Validate that the ID contains only digits and is at least 10 characters
if ( !is_numeric($cedula) || strlen($cedula) < 10 ) {
return response()->json(['error' => 'The ID must contain only digits and be at least 10 characters'], 400);
} else {

// REST API URL
$url = 'https://api/Detection';

// Data to send in the POST request
$data = [
'cedula' => $cedula
];
// Convert data to JSON format
$data_json = json_encode($data);

// Configure HTTP request options
$options = array(
'http' => array(
'header' => "Content-Type: application/json\r\n",
'method' => 'POST',
'content' => $data_json
)
);

// Create the request context
$context = stream_context_create($options);

// Make the request to the REST API
$response = @file_get_contents($url, false, $context);

// Decode the JSON response
$json_response = json_decode($response, true);

// Return the API response
return response()->json($json_response);
}

mi template, desde donde se lo llama en la ruta resources\views\listados\listado_credito.blade.php

// Click event of the "Check balance" button
$(document).on('click', '#consultaBtn', function(event) {
     event.preventDefault(); // Prevent the button's default behavior from being executed
     // let url = 'route("iceBalanceconsultation")';
     console.log("Consult the ICESA_COBRANZA API");
     let url = '../../consultaSaldoIcesa';

     $.ajax({
       type: "POST",
       // Get the route URL using the route() function
       url: url,
       data: {
         'cedula': $("#cedula_icesa").val(),
       },
       success: function(data) {
         // Clear the previous content of the modal
         $('#icesaaccounts').empty();
         if (data && data.length > 0 && data[0].Identity !== 'NO DEBT' && data[0].DetailOpe !== null) {
           // Loop through the details of the operation and display them in the table
           $.each(data[0].DetailOpe, function(index, detail) {
             var row = '<tr>' +
               '<td>' + detail.IdClient + '</td>' +
               '<td>' + detail.Assignor + '</td>' +
               '<td>' + detail.Operation + '</td>' +
               '<td>' + detail.Names + '</td>' +
               '<td>' + detail.Dayslate + '</td>' +
               '<td>' + detail.Product + '</td>' +
               '<td>' + detail.Channel + '</td>' +
               '<td>' + detail.Agency + '</td>' +
               '<td>' + detail.Payment + '</td>' +
               '</tr>';
             $('#icesaaccounts').append(row);
           });
         } else {
           // If there are no transaction details or the identity is NO DEBT, display a message
           $('#accountsIcesa').html('<tr><td colspan="9" class="text-center">There are no details of the operation</td></tr>');
         }
       },
       error: function(data) {
    let message = 'Query failed:' + data.statusText;
         $('#icesaaccounts').html('<tr><td colspan="9" class="text-center">' + message + '</td></tr>');
         console.log(message);
       }
     });
});

log de laravel

[2024-02-15 09:12:48] local.ERROR: InvalidArgumentException: Route [consultaSaldoIcesa] not defined. in C:\xampp\htdocs\Proyectos\domiciliario\vendor\laravel\framework\src\Illuminate\Routing\UrlGenerator.php:314
Stack trace:
#0 C:\xampp\htdocs\Proyectos\domiciliario\vendor\laravel\framework\src\Illuminate\Foundation\helpers.php(695): Illuminate\Routing\UrlGenerator->route('consultaSaldoIc...', Array, true)
#1 C:\xampp\htdocs\Proyectos\domiciliario\storage\framework\views\56a6c3425b8735added597abec95d0fc3b2a4e09.php(395): route('consultaSaldoIc...')

Next ErrorException: Route [consultaSaldoIcesa] not defined. (View: C:\xampp\htdocs\Proyectos\domiciliario\resources\views\listados\listado_credito.blade.php) in C:\xampp\htdocs\Proyectos\domiciliario\vendor\laravel\framework\src\Illuminate\Routing\UrlGenerator.php:314
Stack trace:
#0 C:\xampp\htdocs\Proyectos\domiciliario\vendor\laravel\framework\src\Illuminate\View\Engines\PhpEngine.php(44): Illuminate\View\Engines\CompilerEngine->handleViewException(Object(InvalidArgumentException), 1)
#1 C:\xampp\htdocs\Proyectos\domiciliario\vendor\laravel\framework\src\Illuminate\View\Engines\CompilerEngine.php(59): Illuminate\View\Engines\PhpEngine->evaluatePath('C:\\xampp\\htdocs...', Array)
#2 C:\xampp\htdocs\Proyectos\domiciliario\vendor\laravel\framework\src\Illuminate\View\View.php(149): Illuminate\View\Engines\CompilerEngine->get('C:\\xampp\\htdocs...', Array)

Al llamar a la vista en el AJAX con

let url = '../../CheckApiBalance';

tengo un error 500

lo cambio a

let url = '/CheckApiBalance';

me da un error 404, Not Found

Crei que era algo de la cache, y aplique los siguiente comandos

composer dump-autoload
php artisan cache:clear
php artisan view:clear
php artisan config:clear
php artisan route:clear

pero no obtuve otro error, sin importar lo que haga es el mismo error

PD: No quiero agregar más librerías a mi proyecto de Laraval

3
  • ¿Que pasa si cambias let url = '../../consultaSaldoIcesa' por `let url = '/consultaSaldoIcesa'? Commented el 19 feb. a las 18:30
  • Lo anterior, para tu frontend. Ahora para el backend, laravel tiene un HTTP client para hacer llamadas a una API externa Commented el 19 feb. a las 18:38
  • si le cambio a let url = '/consultaSaldoIcesa'? tengo un error 404 Not Fount
    – Cristian
    Commented el 22 feb. a las 1:00

0

Examina otras preguntas con la etiqueta o formula tu propia pregunta.