How to check request is axios in laravel - laravel

export const category_load = ()=>{
return async (dispatch) => {
await fetch('https://example.com/api/user/categorylist')
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
})
.catch((error) => {
console.error(error);
});
}
}
I sent the axios request to the server.
Here is the server code.
...
if($request->ajax()){
return $Categories;
}
return view(Route::currentRouteName(), compact('Categories'));
If I sent ajax it returns $Categories but I sent axios it returns view.
I have to check axios request like ajax and return $Categories.
How to solve this?

The above answer will work, but it's insecure what if someone gets to know why are you using the additional param and they use it on the browser direct?
Instead, pass header which by default Laravel will read to check if the incoming request is ajax or not.
axios.get(url, {
body:{},
headers: {
"X-Requested-With": "XMLHttpRequest",
},
})
Now you can simply do $request->ajax() in the controller and it will work.

API endpoints are not meant to be used to return views. :) Use non API endpoints to return views.
BTW, with your current implementation you can do this way:
Send an extra parameter, for example, api=true with your Axios request endpoint, as:
export const category_load = ()=>{
return async (dispatch) => {
await fetch('https://example.com/api/user/categorylist?api=true')
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
})
.catch((error) => {
console.error(error);
});
}
Now, in your controller, you can check if the api parameter is set or not. If it's set you can just return the categories like you're doing for the ajax request, as:
// return $Categories if the request is from Axios or Ajax
if($request->ajax() || $request->api == true) {
return $Categories;
}
return view(Route::currentRouteName(), compact('Categories'));

Related

Axios GET with params request shows NULL in Laravel

I am sending some data to my laravel controller using axios get request but the laravel controller shows request null.
my axios request:
const data = {
machine_id: machine_id,
}
const api = "http://192.168.0.108:8000/api/"
const params = JSON.stringify(data)
const headers = {
"Content-Type": "application/json",
}
axios.get(api, { params: params }, headers).then((response) => {
consoleLog("response", response.data)
})
controller:
public function index(Request $request)
{
dd($request->all()); // shows null
}
If I return the response instead of dd() it shows me something like below image:
public function index(Request $request)
{
return $request->all(); // shows data
}
How can I catch the data in controller??
I had the same problem with you. This is what I've done to resolve my problem
let config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
}
}
let params = new UrlSearchParam();
params.append('var1', 'val1');
params.append('var2', 'val2');
//Finally
axios.post('gotourl', params, config).then( ( response ) => {
console.log(response.data);
});

React-Native fetch post to lumen/laravel returns MethodNotAllowed(405) but postman works

I know this questions have been asked before but non of the answers worked for me.
I am working with React Native and sending API's to Lumen-Backend and i realised that all POST request to LUMEN returns 405 error. Tested it with Postman and it works very fine.
Tried using fetch and axios but they all return 405 errors. Find codes Bellow
Postman request working image
FETCH CALL
const BASE_URL = 'http://192.168.43.232/2019/betbank_api/public/api/';
const url = '/app/auth/login/'
const endPoint = BASE_URL.concat(url);
const data ={ email: 'okeke', password:'passs' }
async function postData(url = '', data = {}) {
const response = await fetch(url, {
method: 'POST',
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
headers: {
'Content-Type': 'application/text'
},
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
return await response.text(); // parses JSON response into native JavaScript objects
}
postData(endPoint, { email: 'okeke', password:'passs' })
.then((data) => {
console.log(data); // JSON data parsed by `response.json()` call
alert(data)
});
Also tried implementing the same thing using AXIOS
but ir returns same 405 error. Find Axios code bellow
axios.post(endPoint, data, {
headers: {
'Accept': 'application/json;charset=utf-8',
'Content-Type': 'application/json;charset=utf-8',
}
}).then( (response)=>{
console.log(JSON.stringify(response.data))
alert(JSON.stringify(response.data))
}
).catch( (error)=>{
console.log(error)
alert(error)
})
Find the Lumen Route - API bellow
$router->group(['prefix' => 'api'], function () use ($router) {
$router->post('/app/auth/login', 'AppUserController#postLogin');
});
FInd the method postLogin Bellow
class AppUserController extends Controller
{
protected $jwt;
public function __construct(JWTAuth $jwt)
{
$this->jwt = $jwt;
}
public function postLogin(Request $request)
{
$email = $request->input('email');
$this->validate($request, [
'email' => 'required|email|max:255',
'password' => 'required',
]);
try {
if (! $token = $this->jwt->attempt($request->only('email', 'password'))) {
return response()->json(['status'=>'error','data'=> 'Invalid username and passowrd'], 401);
}
} catch (\Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {
return response()->json(['token_expired'], 500);
} catch (\Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {
return response()->json(['token_invalid'], 500);
} catch (\Tymon\JWTAuth\Exceptions\JWTException $e) {
return response()->json(['token_absent' => $e->getMessage()], 500);
}
return response()->json(compact('token'));
}
}
Everythings seems in order but somehow, neither fetch or axios would work when i use the POST method.
But if i change it to GET method, the error stops but the issue would now be how to get the data's been posted from the APP.
QUESTION
Why would all Post request from my App (React Native) be returning 405 from Lumen/Laravel

Why does promise go into the .then() when the response is an error? - Laravel

I am making a SPA in Laravel with vue.js and vuex and vue router. I made an action in my store for logging, but when I log in with invalid credentials something really strange happens. It works fine when I log in with the right credentials.
So it debugs the following
login
app.js:279 POST http://127.0.0.1:8000/api/auth/login 401
(Unauthorized)
app.js:58018 login succes
app.js:58023 login failed
app.js:43201 Uncaught (in promise) NavigationDuplicated {_name:
"NavigationDuplicated", name: "NavigationDuplicated", message:
"Navigating to current location ("/") is not allowed", stack: "Error↵
at new NavigationDuplicated (http://127.…)↵ at
http://127.0.0.1:8000/js/app.js:57159:12"} message: "Navigating to
current location ("/") is not allowed" name: "NavigationDuplicated"
_name: "NavigationDuplicated" stack: "Error↵ at new NavigationDuplicated (http://127.0.0.1:8000/js/app.js:43124:14)↵ at
HTML5History.confirmTransition
(http://127.0.0.1:8000/js/app.js:43240:18)↵ at
HTML5History.transitionTo (http://127.0.0.1:8000/js/app.js:43184:8)↵
at HTML5History.push (http://127.0.0.1:8000/js/app.js:43515:10)↵ at
http://127.0.0.1:8000/js/app.js:43929:22↵ at new Promise
()↵ at VueRouter.push
(http://127.0.0.1:8000/js/app.js:43928:12)↵ at
http://127.0.0.1:8000/js/app.js:57159:12"
proto: Error
The thing that is crazy to me is that the promise goes into the .then() and console.logs "login succes"? It shouldn't ever get in the .then() right? Because the credentials are wrong, so it should just go for the .catch(). But what is even more strange is that it does nog debug the second console.log(response.data) in the .then()???? Also I do not understand the Navigation Duplicated.
Credentials is just an {username, password}. I am using JWT and the /login route leads to the standard jwt authcontroller login method.
Login.vue component method
methods: {
login() {
this.$store
.dispatch("tryLogin", this.form)
.then(response => {
this.$router.push({ path: "/home" });
})
.catch(error => {
this.logginError = error;
});
}
}
Store action
tryLogin(context, credentials) {
context.commit("login");
console.log("login");
return new Promise((resolve, reject) => {
axios
.post("/api/auth/login", credentials)
.then(response => {
console.log("login succes");
console.log(response.data);
context.commit("loginSucces", response.data);
resolve(response.data);
})
.catch(error => {
console.log("login failed");
context.commit("loginFailed", error);
reject(error);
});
});
}
AuthController login function
/**
* Get a JWT via given credentials.
*
* #return \Illuminate\Http\JsonResponse
*/
public function login()
{
$credentials = request(['email', 'password']);
if (!$token = auth('api')->attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->respondWithToken($token);
}
Ok, I will try to explain (sorry for my english) The following is working fine, when you login with wrong credential it will return a nice JSON response:
if (!$token = auth('api')->attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
That is is not a failure, for that reason it enters to .then and print 401 (Unauthorized)
then it print console.log("login succes") and then when it try to call the context.commit("loginSucces", response.data); it fails and will go to the catch and say app.js:58023 login failed.
You can fix this just asking in the .then
axios
.post("/api/auth/login", credentials)
.then(response => {
if (response.data.status === "error") {
console.log(response.data);
}
else{
context.commit("loginSucces", response.data);
resolve(response.data);
}
})

On get request why do I get back the blade view, when I should get data from the database instead?

I a have the following get request, which is executed on mounted().
In some weird mysterious ways, I get back my main view app.blade as a response when I am clearly requesting some data from the database.
Can someone spot what I messed up?
My get request on the front-end:
mounted() {
this.getProjectRequests();
},
methods: {
getProjectRequests: function() {
var self = this;
let clientId = this.$route.path.substring(
this.$route.path.lastIndexOf("/") + 1
);
axios({
method: "get",
url: "/get-project-requests/" + clientId
})
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(error);
// TODO error handling
});
}
}
My route:
Route::get('/get-project-requests/{client_id}',
'SinglePageController#getProjectRequests');
And my controller method:
public function getProjectRequests($clientId) {
try {
$projectRequests = ProjectRequest::where('client_id',
$clientId)->value('name');
return response()->json( [
'success'=> true,
'projectRequests' => $projectRequests
]);
} catch(\Exception $e){
return ['success' => false, 'message' => 'getting
project requests failed'];
}
}
I think this ProjectRequest::where('client_id', $clientId)->value('name'); giving exception.
Either you check your laravel.log inside storage/logs folder or change that method into
// Not working on eloquent model
$valueOject = ProjectRequest::where('client_id',$clientId)->value('name');
// DB facade its working. Change to this method
$valueOject = DB::table('{your_table}')->where('client_id', $clientId)->value('name');
dd($valueOject);

Sending FormData() with axios in VueJS returns empty array in Laravel

I am trying to post my data using FormData() with axios. Laravel is my Backend.
When I try to dd (die and dump) my $request->all() in my Controller I get an empty array [].
Here's my code which handles the post:
data() {
let formData = new FormData();
formData.append('first_name', 'Max');
formData.append('first_name', 'Sample');
return formData;
}
submit(requestType, url) {
console.log(this.data().get('first_name')); // Output is correctly 'Max'
return new Promise((resolve, reject) => {
axios[requestType](url, this.data())
.then(response => {
this.onSuccess(response.data);
resolve(response.data);
})
.catch(error => {
this.onFail(error.response.data)
reject(error.response.data);
});
});
}
sendData() {
const id = 123;
this.submit(patch, '/persons/' + id);
}
However if I format my data like this:
data() {
let data = {
'first_name': 'Max',
'last_name': 'Sample'
};
return data;
}
I have the right output with dd($request->all() in my Controller.
EDIT
I found the reason for my problem. It is related to the HTTP method patch. If I use post instead the data is send successfully. It must be related to the headers being send but I could not find a solution yet.

Resources