laravel reactjs put all api request in one get request - php

I'm working on a laravel/reactjs project and I use Axios to get data from the database with the Laravel API.
I use the Laravel api.php and web.php for the API calls.
I have a few pages that do multiple requests at the render of the reactjs component but sometimes Laravel throws a random 500 or 403 error when the request are done (1 in 25 or something). Also, calls that go through the web.php have a bit of extra loading time.
So I was wondering if it is a smart idea to make a Laravel function that returns all the data that one page needs at the render. So in react only one get request has to be made at the render.
Is this the best practice or are there any better solutions?
Thanks for helping, If you don't understand the question please tell me.
edit:
the error returned by Laravel :
{
"message": "Server Error"
}{
"message": "Server Error"
}

I would suggest increasing the API throttle in app/Http/Kernal.php, you can also use Route::dispatch to call routes internally and then group them in a single response:
// GET Request
$request = Request::create('/some/url/1', 'GET');
$response = Route::dispatch($request);
// POST Request
$request = Request::create('/some/url/1', 'POST', Request::all());
$response = Route::dispatch($request);

Related

Problem with CORS loading data from cakephp restapi implementation into angular app

I'm trying to comunicate with an already working RestAPI server developed in PHP (CakePHP framework); i'm trying to make a simple login action in Angular 7 application and if success i will proceed with the implementations.
This is the Angular App call code:
constructor(protected cli: HttpClient) {
this.tablet_couple = new TabletCoupleModule();
}
ngOnInit() {
this.cli.get('http://work.local/grai/api-angular/api/v1/tablet_couples/1.json')
.subscribe(
data => { console.log(data) }
)
this.cli.post('http://work.local/grai/api-angular/api/v1/tablet_couples/login.json',{
username: 'xxxxxxxx',
passoword: '123456789',
})
.subscribe(
data => { console.log(data) }
)
}
The actual problem is that the GET call work fine, but the POST call still no working.
I'm sure the REST API is working correctly because if i use tool like Insomnia the response is correct for both calls.
I try to find why but the problem is every time the CORS implementation:
I have try to force headers in Cakephp as you can see above but still not working.
public function beforeFilter(\Cake\Event\Event $event)
{
parent::beforeFilter($event);
if($this->request->is('OPTIONS')) {
$this->response->header('Access-Control-Allow-Origin','*');
$this->response->header('Access-Control-Allow-Methods','*');
$this->response->header('Access-Control-Allow-Headers','Content-Type, Authorization');
}
else {
$this->response = $this->response->withHeader("Access-Control-Allow-Origin","*");
$this->response = $this->response->withHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept");
$this->response = $this->response->withHeader("Access-Control-Allow-Methods","*");
}
}
UPDATE 1
I had find a library to integrate CORS with cakephp : cakephp-cors
This help but i still have a problem: i can't use Rest API if they are not on the same domain (ok is CORS) but i need.
IF i deploy the application and put my Angular App on the same domain it works; but i want deploy app that can access remote REST API.
Any suggestion?
Ok, i had a "solution" tanks to the #JensV.
1th :: cakephp 3.1.x is too old
I'm using an OLD version of CakePHP (3.1.14); the 3.1.x is simply too old to manager correctly an OPTIONS Method Call.
Using CakePHP 3.7.* with the plugin cakephp-cors it works correctly and now i can make remote call from localhost:4200 .
2nd :: the Method OPTIONS
This is a method that give me so much pain; this method is called by browsers before a POST method call.
The correct response at this method is a HTTP Code 200 from the server.
If you don't manage this call correctly the browser truncate the POST call.
Again i post some reference about this call and how to find a solution:
CakePHP, preflight & CORS
Handling “XMLHttpRequest” OPTIONS Pre-flight Request in Laravel
I hope it helps someone.

How do I integrate a Symfony controller action in a legacy PHP page?

I do have a legacy PHP application and a Symfony 4.1 application. I need to integrate both by rendering parts of a plain PHP page as the result of a predetermined controller action. That is, no resolving based on request is necessary or wanted and the response body should be inserted in the legacy page.
Put differently: I want Symfony to act on the current request, but in advance tell it to use ExampleController::exampleAction() and get the response (body). What is the cleanest way to achieve that?
Well, this is weird :)
I would try something like this:
1, Get an instance of your kernel. Check public/index.php about how to do that.
$kernel = new Kernel($env, $debug);
2, Create a request manually
$request = new Request([], [], ['_controller' => MyController::class . '::myAction']);
3, Handle the request
$kernel->handle($request);
4, Send the response, and terminate the kernel (like in index.php)
Tested it with a custom front controller, see https://gist.github.com/Padam87/27a7d0825816fa358678bce7a640dd47
If you only need the response body, then use $response->getContent().

Sub request in Laravel 5

I'm looking to do sub requests in my API, to other parts of my API. I have done this before in Symfony - but I'm not sure how to achieve this in Laravel.
$url = route('some.route', ['param' => $val]);
$request = Request::create($url, 'get', []);
Route::dispatch($request);
Always seems to fail giving something along the lines of
Class api does not exist
So I've tried
app()->handle($request);
This works, but processes a request, but I cant handle any exceptions thrown (e.g. validation as the app layer handles it and throws a html response)
Handle has a signature of the HttpKernelInterface, so can take a property of sub requests and catch exceptions - but these are not used....
...->handle($request, HttpKernelInterface::SUB_REQUEST, false);
Is it possible to do this in Laravel without having to send an actual http request?
Thanks
So after digging deep into the framework, it seems that this way is not possible as it stores some values as statics and they're not updated via the dipatch() method.
So ive created this package to handle setting and reapplying the original values.
https://github.com/myerscode/laravel-sub-request

Where does laravel 5 handle the ValidationException?

If the incoming request was an AJAX request, no redirect will be
generated. Instead, an HTTP response with a 422 status code will be
returned to the browser containing a JSON representation of the
validation errors.
This is not working! I am trying to access the route via an ajax request and it redirects back.
If validation passes, your code will keep executing normally. However, if validation fails, an Illuminate\Contracts\Validation\ValidationException will be thrown. This exception is automatically caught and a redirect is generated to the user's previous location. The validation errors are even automatically flashed to the session!
Now I want to know where does laravel catch this exception so that I can modify it?
This is handled inside the FormRequest class:
protected function failedValidation(Validator $validator)
{
throw new HttpResponseException($this->response(
$this->formatErrors($validator)
));
}
You can override this function in your own Request object and handle a failed validation any way you like.
After been researching for a while I will post my results so anyone with this problem saves a lot of time.
#Faiz, you technically shouldn't change a thing if you want to stick to laravel behavior (I'll always try to follow taylor's recommendations). So, to receive a 422 response code status you need to tell phpunit you will send a XMLHttpRequest. That said, this works on laravel 5
$response = $this->call('POST', $url, [], [], [],
['HTTP_X_Requested-With' => 'XMLHttpRequest']);
More information at Github Issues. Besides, if you look at Symfony\Component\HttpFoundation\Request#isXmlHttpRequest you will find that this header is used by "common JavaScript frameworks" and refers to this link
Haven't tested on the browser yet, but I think this should work too.

How Follow the Don't Repeat Yourself Principle When Consuming My Own Laravel API?

I'm developing a Laravel 4 app that will make the same CRUD operations on my data set available through a JSON REST API and a Web UI. It seems that to prevent breaking the DRY principle that my UI should consume my own API by routing all requests from the UI back to the API. I'm unsure though about the best approach to making this work. Presumably I would have separate UI and API controllers and somehow route the requests through. Or should I be looking at a different approach altogether?
I'm actually tinkering with the same idea and it's pretty neat. With Laravel you do have the ability to make internal requests (some might refer to this as HMVC, but I won't). Here's the basics of an internal request.
$request = Request::create('/api/users/1', 'GET');
$response = Route::dispatch($request);
$response will now contain the returned response of the API. Typically this will be returned a JSON encoded string which is great for clients, but not that great for an internal API request. You'll have to extend a few things here but basically the idea is to return the actual object back through for the internal call, and for external requests return the formatted JSON response. You can make use of things like $response->getOriginalContent() here for this kind of thing.
What you should look at doing is constructing some sort of internal Dispatcher that allows you to dispatch API requests and return the original object. The dispatcher should also handle malformed requests or bad responses and throw exceptions to match.
The idea itself is solid. But planning an API is hard work. I'd recommend you write up a good list of all your expected endpoints and draft a couple of API versions then select the best one.
NOTE: As vcardillo pointed out below, route filters are not called with these methods.
I am currently doing the same thing, and Jason's answer got me going in a great direction. Looking at the Symfony\Component\HttpFoundation\Request documentation, I figured out how to POST, as well as everything else I'd need to do. Assuming you're using a form, here is some code that could help you:
GET:
$request = Request::create('/api/users/1', 'GET');
$response = Route::dispatch($request);
POST:
$request = Request::create('/api/users/1', 'POST', Input::get());
$response = Route::dispatch($request);
POST w/ cookies
$request = Request::create('/api/users/1', 'POST', Input::get(), Cookie::get('name'));
$response = Route::dispatch($request);
POST w/ files
$request = Request::create('/api/users/1', 'POST', Input::get(), null, Input::file('file'));
$response = Route::dispatch($request);
I hope this helps someone else. If you aren't using a form, or you are but not using Laravel's Input / Cookie facade, replace the Input / Cookie facades with your own content.
Taylor Otwell suggested using app()->handle() rather than Route::dispatch() to achieve a clean request.
For Route::dispatch($request) I noticed if the endpoint of your non-GET request (parameters on the HTTP request body) uses a dependency injected \Illuminate\Http\Request or \Illuminate\Foundation\Http\FormRequest extending instance, state of the parameters, cookies, files, etc. are from the original HTTP request. i.e., for your application's controller action method.
If parameter names and post method type for your app controller and API controller are the same, you won't notice the difference since the original parameter values are passed on. But when you're manually assembling the 3rd parameter of Request::create(), Route::dispatch() will result in it being ignored.
app()->handle() fixes that context problem in the Laravel request lifecycle.
Caveat: app()->handle() affects Illuminate\Support\Facades\Request, refreshing it with this new request instance. As a knock-on effect, calls like Request::isXmlHttpRequest() or redirect()->back() invoked after app()->handle() will cause unpredictable behaviour. I'd suggest tracking the context of your original request and instead use redirect()->to(route('...')) so you strictly control flow and state of your app.
Given all these corner cases, it may be best to just do a manual curl using a Guzzle HTTP client.
If you are looking for using passport login api internally, then you need to add the parameters to original request:
protected function manualLogin(Request $request)
{
$email = $request->input('email');
$password = $request->input('password');
$request->request->add([
'username' => $email,
'password' => $password,
'grant_type' => 'password',
'client_id' => $clientID,
'client_secret' => $clientSecret,
'scope' => '*']);
$newRequest = Request::create('/oauth/token', 'post');
return Route::dispatch($newRequest)->getContent();
}
If you're consuming your own API, use app()->handle() instead of Route::dispatch() as Derek MacDonald has suggested.
app()->handle() creates a fresh request, while Route::dispatch() runs the route within the stack, effectively ignoring parameters that are part of the request that you're sending.
Edit: Just a heads-up. Taylor Otwell advises against using sub-requests to make internal API calls, as they mess the current route. You can an HTTP API client like Guzzle instead to make the API calls.
You can use Optimus API consumer, the API is clean and simple, example making an internal request:
$response = app()->make('apiconsumer')->post('/oauth/token', $data);
In it's core, it uses Illuminate\Routing\Router and Illuminate\Http\Request to make the call
// create the request
$this->request->create($uri, $method, $data, [], [], $server, $content);
// get the response
$response = $this->router->prepareResponse($request, $this->app->handle($request));

Categories