Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Lithe
Lithe

Posted on • Edited on

     

Integrating PHP with React Using Lithe

In this post, we will learn how to integrate the Lithe framework with the React library, highlighting how Lithe seamlessly integrates with frontend libraries. In addition to being excellent for building APIs, Lithe makes it easy to access your application's resources by efficiently configuring CORS (Cross-Origin Resource Sharing) to ensure that your applications communicate securely and effectively.

Step 1: Setting Up the Environment

1. Installing Lithe

First, install Lithe if you haven't done so already. Run the following command in the terminal:

composer create-project lithephp/lithephp project-namecdproject-name
Enter fullscreen modeExit fullscreen mode

2. Installing React

Next, create a new React project inside your Lithe project. Run:

npx create-react-app frontendcdfrontend
Enter fullscreen modeExit fullscreen mode

Step 2: Installing and Configuring CORS

1. Installing the CORS Module

To use the CORS middleware in your Lithe project, you need to install thelithemod/cors package. Run the following command:

composer require lithemod/cors
Enter fullscreen modeExit fullscreen mode

2. Using the CORS Middleware

After installation, you need to configure the CORS middleware in your Lithe application. Open the main filesrc/App.php and add the following code:

If you want to allowmultiple origins to access your API, configure CORS as follows:

usefunctionLithe\Middleware\Configuration\cors;$app=new\Lithe\App;$app->use(cors());$app->listen();
Enter fullscreen modeExit fullscreen mode

On the other hand, if you want only your React application to consume the API, use the following configuration:

$app->use(cors(['origins'=>['http://localhost:3000']]));
Enter fullscreen modeExit fullscreen mode

Step 3: Configuring the Backend with Lithe

1. Creating an API Route

In your Lithe project, create a new router to provide data to React. Create a route file, such assrc/routes/api.php:

useLithe\Http\{Request,Response};usefunctionLithe\Orbis\Http\Router\{get};get('/data',function(Request$req,Response$res){$data=['message'=>'Hello from Lithe!','items'=>[1,2,3,4,5],];return$res->json($data);});
Enter fullscreen modeExit fullscreen mode

After defining the route file, you need to add the router to your Lithe application. Open the main filesrc/App.php again and add the following code before calling thelisten method:

// ...usefunctionLithe\Orbis\Http\Router\router;$apiRouter=router(__DIR__.'/routes/api');$app->use('/api',$apiRouter);// ...
Enter fullscreen modeExit fullscreen mode

Thesrc/App.php file will look like this:

usefunctionLithe\Middleware\Configuration\cors;usefunctionLithe\Orbis\Http\Router\router;$app=new\Lithe\App;$app->use(cors());$apiRouter=router(__DIR__.'/routes/api');$app->use('/api',$apiRouter);$app->listen();
Enter fullscreen modeExit fullscreen mode

2. Testing the Route

Start the Lithe server with the following command:

php line serve
Enter fullscreen modeExit fullscreen mode

Accesshttp://localhost:8000/api/data to ensure that the JSON is returned correctly.

Step 4: Configuring the Frontend with React

1. Consuming the API in React

Open thesrc/App.js file in your React project and replace its content with:

importReact,{useEffect,useState}from'react';functionApp(){const[data,setData]=useState(null);useEffect(()=>{fetch('http://localhost:8000/api/data').then(response=>response.json()).then(data=>setData(data)).catch(error=>console.error('Error fetching data:',error));},[]);return(<div><h1>IntegratingPHPwithReactusingLithe</h1>{data?(<div><p>{data.message}</p><ul>{data.items.map((item,index)=>(<likey={index}>{item}</li>))}</ul></div>):(<p>Loading...</p>)}</div>);}exportdefaultApp;
Enter fullscreen modeExit fullscreen mode

2. Starting the React Server

To start the React development server, run:

npm start
Enter fullscreen modeExit fullscreen mode

Step 5: Verifying the Integration

Accesshttp://localhost:3000 in your browser. You should see the message "Hello from Lithe!" and a list of items returned by the API.

Final Considerations

With this, you have successfully integrated Lithe with React and configured CORS to allow only the React application to access backend resources or to allow multiple origins as needed. Now you can expand your application as desired.

Feel free to share your experiences and questions in the comments!

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Dynamic and adaptable PHP framework.
  • Pronouns
    LithePHP
  • Joined

More fromLithe

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp