To make a GET request to a Laravel API using JavaScript's Fetch API, you will typically follow these steps:
First, ensure you have a Laravel API set up. Below is an example for fetching users from a database.
Define the Route:
In routes/api.php
, define a route for fetching users:
use App\Http\Controllers\UserController;
Route::get('/users', [UserController::class, 'index']);
Create the Controller Method:
In UserController.php
, implement the index
method to return users:
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function index()
{
$users = User::all(); // Fetch all users
return response()->json($users); // Return users as JSON
}
}
You can use the Fetch API to make a GET request from your frontend code (HTML/JavaScript). Here’s a simple example:
HTML Structure:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fetch Users</title>
</head>
<body>
<h1>Users List</h1>
<ul id="user-list"></ul>
<script src="app.js"></script> <!-- Link to your JavaScript file -->
</body>
</html>
JavaScript Fetch Request:
In a file named app.js
, you can write the Fetch API code to get the users:
document.addEventListener('DOMContentLoaded', () => {
// Function to fetch users from the API
function fetchUsers() {
fetch('http://your-app.test/api/users') // Replace with your API URL
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok ' + response.statusText);
}
return response.json(); // Parse JSON response
})
.then(data => {
const userList = document.getElementById('user-list');
userList.innerHTML = ''; // Clear existing list
// Populate the user list
data.forEach(user => {
const listItem = document.createElement('li');
listItem.textContent = `${user.name} (${user.email})`; // Customize as needed
userList.appendChild(listItem);
});
})
.catch(error => {
console.error('There was a problem with the fetch operation:', error);
});
}
fetchUsers(); // Call the function to fetch users
});
If your Laravel API and frontend are running on different origins (different domains or ports), you might encounter CORS issues. To enable CORS in Laravel, you can use the Laravel CORS package.
You can install it via Composer if it isn't already included in your project:
composer require fruitcake/laravel-cors
After installing, configure the CORS settings in config/cors.php
to allow requests from your frontend's origin.
In this guide, you learned how to:
This process allows you to integrate your Laravel backend with a frontend application, enabling dynamic data fetching and display.
@aCodeTutorials All Rights Reserved
privacy policy | about