How to get http response from lumen API asynchronously - laravel

Lumen is sending response to the client side according to the order of requests. It is holding next response until previous response completes. I need to make it asynchronously
Laravel Lumen Routing Code:
$router->get('waist-xxxxxxx/v20/', ['uses' => 'DemoController#fnDemoFunction']);
$router->get('waist-xxxxxxx/v20/{serverSideRowUuid}', ['uses' => 'DemoController#fnDemoFunction']);
$router->post('waist-xxxxxxx/v20/', ['uses' => 'DemoController#create']);
$router->put('waist-xxxxxxx/v20/{serverSideRowUuid}', ['uses' => 'DemoController#update']);
$router->options('waist-xxxxxxx/v20', function () {
return response('OK', \Illuminate\Http\Response::HTTP_NO_CONTENT)
->header('Access-Control-Allow-Credentials', 'true')
->header('Connection', 'keep-alive');
});
$router->options('waist-xxxxxxx/v20/{serverSideRowUuid}', function () {
return response('OK', \Illuminate\Http\Response::HTTP_NO_CONTENT)
->header('Access-Control-Allow-Credentials', 'true')
->header('Connection', 'keep-alive');
});
Vue.js App code for API calling:
export default {
methods: {
async mxGetDataFromDb() {
/*
TODO: Need to restrict the load to current data
api is vuex-orm-axios plugin function
When using json-server backend the code is:
*/
console.log('reminders req sent')
const proRemsFromDB = await clientSideTable.api().get(clientSideTable.apiUrl)
console.log('reminders recd')
if (proRemsFromDB.ok) {
}
},
},
}
Here is a screenshot for better understanding: enter image description here

I suspect you're using php artisan serve to test with.
This command utilizes the built-in PHP development server. It's a great tool, but it can only handle one request at a time:
The web server runs only one single-threaded process, so PHP applications will stall if a request is blocked.
In general, while php artisan serve is great for quick testing, you'll want to set up something like Laravel Homestead or some other more robust development environment long-term.

Related

Laravel passport 404, Trying to connect a front end client to Laravel back-end api

Please help explain me a bit. I'm very new to this back-end, OAuth 2.0. I'm trying to make my Laravel project to become an api with Passport authorization system. But after following the passport installation guide from official documents and watching youtube tutorials, I still can't connect Laravel to my front end. Can you please point out what I'm missing ? Sorry if this question is super vague, I don't really understand much what's going on.
How and where do I create a new client for my passport back end api ? Should this code be in my front end (or in laravel?) ?
const data = {
name: 'Client Name',
redirect: 'http://example.com/callback'
};
axios.post('/oauth/clients', data)
.then(response => {
console.log(response.data);
})
.catch (response => {
// List errors on response...
});
In the official documents which talks about issuing access tokens with JSON api, there's this explanation.
However, you will need to pair Passport's JSON API with your own frontend to provide a dashboard for your users to manage their clients. Below, we'll review all of the API endpoints for managing clients. For convenience, we'll use Axios to demonstrate making HTTP requests to the endpoints.
The JSON API is guarded by the web and auth middleware; therefore, it may only be called from your own application. It is not able to be called from an external source.
It didn't explain how I could pair my frontend to this Laravel app. I tried adding this to my front end javascript.
const BASE_URL = 'http://127.0.0.1:8000/api';
**
* Trying Passport JSON api to get all clients for a given user.
*/
const getClients = async () => {
try {
const response = await axios.get(`${BASE_URL}/oauth/clients`);
const clients = response.data;
console.log('Here are your clients', clients);
} catch (errors) {
console.error(errors);
}
}
/**
* Trying to create a new client. Not sure if this is equivalent to linking this external app to the backend api or not
*/
const addClient = async() => {
const data = {
name: 'front end jajaja',
redirect: 'http://www.google.com'
};
const response = await axios.post(`${BASE_URL}/oauth/clients`, data);
console.log(response.data);
}
/**
* main function to test it all
*/
const main = () => {
addClient();
// getClients();
}
main();
but after I ran npm run dev and the main() method is called from the front end, console displayed an error saying
POST http://127.0.0.1:8000/api/oauth/clients 404 (Not Found)
I haven't edit routes/api.php.
<?php
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
And from a tutorial by Andrew, he said he used Laravel breeze to make a mock client, but can I use my super simple front end JavaScript instead ? Can you please explain me, how can I connect my front to the back ? How can I get the authorization code, client secret ??

nuxtjs middleware rest API raw data requests

I have build nuxtjs example with built in rest API requests with middleware technique. In index.js of my middleware section I put some code :
export default {
handler(req, res) {
res.write('Everything ok!')
console.log(req);
console.log(res);
res.end()
},
path: '/test15'
}
When I call http://ip:port/test15/?cmd=somecmd&param=testparam
In console.log I get params data in log, everything nice. No matter which method used, post or get, it also fixed in log.
The problem is when I try to send raw data (ex json) in request body or form data. I can`t see them in any log output.
So question is, is it possible to send some data in such requests via middleware ?
Thanks!
middleware in nuxt is a sandwich for internal routes aka client side. For your question serverMiddleware is the answer that work on the server side. You can checkout more here
Quick example:
In your nuxt.config.js file add like below
serverMiddleware: [
{ path: '/api/subscribe', handler: '~/api/subscribe' }
],
Then create an api folder you can create subscribe.js file to add relative api route.
import express from 'express'
const app = express()
app.get('/subscribe', async (req, res) => {
res.send('love to the world');
})
export default {
path: '/api',
handler: app
}

How to use Auth::check or Auth::user between different domains?

I've got a question regarding Laravel framework (vers. 5.2) and the authentication. I have 2 domains which represent a software. let's call them https://azure.mydomain.com and https://azuresoftware.mydomain.com.
The Laravel application is hosted on the domain https://azuresoftware.mydomain.com. https://azure.mydomain.com is just a CMS framework which is providing some information about the website.
Now I want to display different menus, if the user is logged in or not on https://azure.mydomain.com. I thought, I can do a fetch request to https://azuresoftware.mydomain.com/ and use the Laravel methods Auth::check() to check if the user is already logged in or not. I know that this is a CORS fetch request, but this is not the issue. I've allowed in the IIS webserver requests from https://azure.mydomain.com. The request works fine and also just a simple request. But actually Auth::check() is always returning false, even when I'm logged in on the software side.
This is my code so far:
<script>
fetch('https://azuresoftware.mydomain.com/checkLogin', {
method: 'GET',
headers: {
'Content-Type': 'text/plain'
}
})
.then(function(res) {
return res.json()
})
.then(function(data) {
if(data.isLoggedIn) {
// do some stuff...
}
else
{
// do some other stuff...
}
});
</script>
routes.php:
Route::group(['middleware' => 'web'], function () {
...
Route::get('checkLogin', function() {
return json_encode(['isLoggedIn'=>\Auth::check()]);
});
...
I'm sure, I forgot something essential, why it is not working this way.
This is due to the fact that AJAX calls only send cookies if the url you're calling is on the same domain as your calling script.
See Cross domain POST request is not sending cookie Ajax Jquery for more information.

Axios Get request return html not data SPA

need some help. I'm trying to fetch data from my db using axios. My backend is Laravel. I have a 200 status http request but it returns the whole html not the data I'm expecting.
Here is my code for route
Route::get('/home', 'PostController#ajaxCall');
Route::post('/home', 'PostController#store');
Route::get('/{any?}', function () {
return view('welcome');
});
Here is my code for Home.vue for Axios request
export default {
components: {addForm},
data () {
return{
posts:[]
}
},
created() {
axios.get('/home').then(response => this.posts = response.data);
}
}
For my controller
public function ajaxCall(){
return response(Post::all());
}
It looks like you get to the ajaxCall() method by using the route '/home', but with axios, you are hitting "/" which returns a view called Welcome. Maybe you need to change the path you use in axios to '/home'?
It might be late but maybe someone else is looking for the solution
I was also facing this in SPA using laravel and VUE.
Route::get('/{any}', 'SinglePageController#index')->where('any', '.*');
SPA has this route, so whenever you write any other get route your app will redirect you to the home page, to avoid this either move this route at the end of your web.php
or write your other routes in api.php file.
In my case i solved it by changing the GET method to POST method.
Try that. It might help

laravel_token is valid for first request but not subsequent requests

I have installed Laravel Passport and configured it according to the documentation. When calling axios.get from my VueJS file, the first call works as expected. the laravel_session Request Cookie is injected into the request, and the authentication passes, returning the resource.
My problem arises when I try to call the axios.get method again. My use case here is a search function. I'm making a call to /api/banking/accounts/search/{search-term} whenever the user types into a text field, using the code below:
remoteMethod(query) {
if (query !== '') {
this.loading = true;
axios.get(
`/api/banking/accounts/search/${escape(query)}`
).then(res => {
this.destinationAccountDirectory = res.data;
this.loading = false;
});
} else {
this.destinationAccountDirectory = [];
}
},
This code works fine without any auth:api middleware on the route, and for the first time with auth:api middleware. As can be seen from the screenshots below, the laravel_token value changes and is rejected on subsequent calls to the API.
**I've tried to removed the \Laravel\Passport\Http\Middleware\CreateFreshApiToken that was added to the web middleware group during passport installation, which seemed to have temporarily solved the issue, until I receive a 419 on a request shortly after. What could be causing the new laravel_tokens to be rejected? **
I solved this by removing the web middleware from my API route. Why it was there in the first place, I have no idea.
I changed my api.php from
Route::group([
'middleware' => [
'web',
'auth:api']], function() {
Route::post('/banking/transactions', 'TransactionController#store');
Route::get('/banking/accounts', 'BankAccountDirectoryController#index');
Route::get('/accounts/{account}', 'BankAccountDirectoryController#show');
Route::get('/banking/accounts/search/{term?}', 'BankAccountDirectoryController#search');
});
to
Route::group([
'middleware' => [
'auth:api']], function() {
Route::post('/banking/transactions', 'TransactionController#store');
Route::get('/banking/accounts', 'BankAccountDirectoryController#index');
Route::get('/accounts/{account}', 'BankAccountDirectoryController#show');
Route::get('/banking/accounts/search/{term?}', 'BankAccountDirectoryController#search');
});
Should the API routes be under the web group to benefit from the middleware, or is it purely for UI? Am I safe to do this?

Resources