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);
});
Related
this the function for API in laravel for search:
public function search(Request $request) {
try {
$request->validate(['search' => ['max:15', 'required']]);
$search = $request->input('search');
$answerSearch = Answer::where('title','like', '%'.$search.'%')->get();
return AnswersResource::collection($answerSearch);
}catch(\Exception $e){
return response()->json(['status'=>false, 'msg'=> $e->getMessage()], 500);
}
}
}
in postman it works like a charm and expected
but with the flutter this is the code to work with this API:
Future<List<AnswerData>> searchAnswers({required String search}) async {
final response = await post(
Uri.parse("$_url/search"),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{"search" : search})
);
final answers = answerFromJson(response.body);
print("fdfsdfdsfdsf ${answers.data}");
return answers.data;
}
}
its return null ?
Check the response status by printing 'response.statusCode'.
print('Response status: ${response.statusCode}');
I have a controller called CartController.php
In this controller I have two methods:
public function store(Request $request)
{
// we'll check to see if the order is already in db
$productOrderDetails = new \App\Cart;
$productOrderDetails->session_id = session()->getId();
$productOrderDetails->job_name = $request->jobName;
$productOrderDetails->pro_name = $request->productName;
$productOrderDetails->save();
return response()->json($request);
}
public function displayCart()
{
//dd($upsCost);
$currentSessionID = session()->getId();
$displayCart = Cart::where('session_id', $currentSessionID)->get();
dd($currentSessionID);
session(['inCartDetails' => $displayCart]);
return view('layouts.cart')->with('cartDetails', $displayCart);
}
The store method is hit by a fetch api post.
export async function postProductDetails(details) {
const url = 'http://127.0.0.1:8000/api/cartDetails';
let response = await fetch(url, {
method: 'POST',
mode: 'cors',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(details)
})
if(response.ok) {
window.location.href = "/cart";
} else {
alert("HTTP-Error: " + response.status);
}
// return response.json();
}
My problem is that I'm getting two different session ids.
When the method store is hit via the fetch post I get the session id:
HnSxCjSXflzyt4Uks3SGsEZcJEHleSR97N1RNA5l
Then when I run the method displayCart it gives me a different session id:
su8A6E3umTW1XmXf5Yhk3SHU5WUGCEpcJWXlnVIP
It's being accessed from same browser, with in a couple of minutes. Any idea why this is happening?
I would not rely on the session ID for your logic, You could however create a Cart and save the Cart ID to the session and then retrieve it:
public function store(Request $request)
{
$productOrderDetails = new \App\Cart;
$productOrderDetails->job_name = $request->jobName;
$productOrderDetails->pro_name = $request->productName;
$productOrderDetails->save();
session(['cart_id' => $productOrderDetails->id]);
return response()->json($request);
}
public function displayCart()
{
$displayCart = session('cart_id') ? Cart::find(session('cart_id')) : null;
return view('layouts.cart')->with('cartDetails', $displayCart);
}
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
I want to return user details from Laravel via Angular http.get() method, but its returning null from laravel.Everything is working fine except http.get() method.
Angular code
app.component.ts
this.userdetailservice.getuserdetails(44).subscribe(
(response) => {
console.log(response);
},
(error) => {console.log(error); }
);
userdetailservice.ts
url = 'http://localhost:8080/laravel_angular/blog/public/api/geteachuserdetail';
constructor(private http: HttpClient) { }
getuserdetails(id: any)
{
const headers = new HttpHeaders().set('Content-type', 'Application/json');
const myparams = new HttpParams();
myparams.set('id', id);
return this.http.get<any>(this.url, { headers: headers, params: myparams});
}
Laravel end
api.php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, GET, POST");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
Route::get('/geteachuserdetail', "UserloginController#geteachuserdetail");
UserloginController.php
public function geteachuserdetail(Request $request) {
$id=$request->input('params');
echo json_encode(array('userdetail'=>$id));
}
Try this:
Route::any('/geteachuserdetail', "UserloginController#geteachuserdetail");
and
public function geteachuserdetail(Request $request) {
$id = $request->input('params');
return response()->json(array('userdetail' => $id));
}
And you can try request you api with other tools like Postman, look the response code and the response content.
I'm trying to set axios request but always getting missing argument, but not sure how can I pass it can someone explain why this wont work?
my route: (web.php)
Route::post('/api/setSuccessMessage', 'API\SessionsController#setSuccessMessage');
my controller: (Controllers/API/SessionsController.php)
class SessionsController extends Controller
{
public static function setSuccessMessage($key, $value)
{
session()->put($key ,$value);
}...
and my vueJS axios call (resources/assets/components/Login.vue)
created: function () {
// check is user logged out
axios.post('/api/setSuccessMessages', {message: 'message',message2: 'message2'}).then((response)=> {
console.log(response);
})
},
Use :
public static function setSuccessMessage(Request $request)
{
$key = $request->get('message');
$value = $request->get('message2');
session()->put($key ,$value);
}
If you want to send the data as a part of your request body you can do so like
axios.post('/api/setSuccessMessages', {message: 'message',message2: 'message2'})
.then((response)=> {
console.log(response);
}
)
//you then accept them as such
Route::post('/api/setSuccessMessage/{message}/{message2}', 'API\SessionsController#setSuccessMessage');
If you wish to send the data as a request params (everything after ? in the url) you can do so like this
var params = {
message1: message1,
message2: message2
};
axios.post('/api/setSuccessMessages', {}, {'params': params})
.then((response)=> {
console.log(response);
}
)
//you then accept them as such
Route::post('/api/setSuccessMessage', 'API\SessionsController#setSuccessMessage');
//You can further use them as such in controller
function public test(Request $request) {
$request->get('message1');
$request->get('message2');
}
I'll reference axios official docs for the axios request params