How to get parameter from angular get method in laravel? - 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.

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

laravel simple axios with argument

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

Angular 2+ and Laravel - Internal Server Error

For post request from Angular to Laravel I am getting error(Internal Server Error). But it successfully works in Postman.
api.php
<?php
use Illuminate\Http\Request;
Route::post('/addHouse', [
'uses' => 'HouseController#postHouse'
]);
HouseController.php
public function postHouse(Request $request)
{
$house=new House();
$house->houseName=$request->input('houseName');
$house->type=$request->input('type');
$house->for=$request->input('for');
$house->address=$request->input('address');
$house->price=$request->input('price');
$house->description=$request->input('description');
$house->bedrooms=$request->input('bedrooms');
$house->bathrooms=$request->input('bathrooms');
$house->area=$request->input('area');
$house->save();
return response()->json([
'house'=>$house
],201);
}
Cors.php(Middleware)
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin','*')
->header('Access-Control-Allow-Methods','Get, POST, PUT, PATCH, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers', 'Content-type, Authorization');
}
In Angular house.service.ts
addHouse(content) {
console.log(content);
const body = JSON.stringify({
content: content
});
const headers = new Headers({
'Content-Type':'application/json'
});
return this._http.post('http://localhost:8000/api/addHouse', body, {
headers: headers
});
}
My error -> POST http://localhost:8000/api/addHouse 500 (Internal Server Error)
I solved it by changing addHouse function. Thanks everyone..
addHouse(data) {
var headers = new Headers();
headers.append (
'Content-type','application/json'
);
return this._http.post('http://localhost:8000/api/addHouse', JSON.stringify(data), {
headers:headers
}).map(res => res.json());
}

Angular 2 Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response

I'm using codeigniter REST API for my server application. And client as Angular2, in my REST API I have given basic auth. I have set like
$config['rest_auth'] = 'basic';
And
$config['rest_valid_logins'] = ['uname' => 'pwd'];
And also for CORS Check i have used below code,
$config['check_cors'] = TRUE;
$config['allowed_cors_headers'] = [
'Origin',
'X-Requested-With',
'Content-Type',
'Accept',
'Access-Control-Request-Method'
];
$config['allowed_cors_methods'] = [
'GET',
'POST',
'OPTIONS',
'PUT',
'PATCH',
'DELETE'
];
$config['allow_any_cors_domain'] = TRUE;
And also I have tried explicitly tried with in my rest controller,
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Content-Range, Content-Disposition, Content-Description');
I used below code in angular,
import { Component, OnInit } from '#angular/core';
import { Http, Headers, RequestOptions } from '#angular/http';
import { FormGroup, AbstractControl, FormBuilder, Validators } from '#angular/forms';
import { Router } from '#angular/router';
import { CommonService, BaseAPIURL } from '../common/common.service';
export class Login implements OnInit {
private headers: Headers;
constructor(fb: FormBuilder, private router: Router, private http: Http,
private commonService: CommonService) {
this.headers = new Headers();
this.headers.append('Authorization', 'Basic ' + btoa('uname:pwd'));
this.headers.append('Content-Type', 'application/json');
}
ngOnInit() {
}
public onSubmit(values: Object): void {
this.submitted = true;
if (this.form.valid) {
let options = new RequestOptions({ headers: this.headers });
this.http.post(this.getuserLoginURL, JSON.stringify(values), options ).subscribe(
response => {
let result = response.json();
this.errorMessage = result.message;
},
error => {
this.isDisabled = false;console.log(error);
if (error.status == 400) {
this.errorMessage = JSON.parse(error._body).message;
} else {
this.errorMessage = 'Internal server error. please contact admin.';
}
}, () => {
});
}
}
}
When i have check with postman it is working well without any issue. When check with angular error comes like,
XMLHttpRequest cannot load http://localhost:97/sencogold/index.php/Adminaccount_api/login_adminuser. Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.
If i false the rest auth and remove the Authorization header it is working well without check the api user name and password
$config['rest_auth'] = FALSE;
and in angular
this.headers = new Headers();
//this.headers.append('Authorization', 'Basic ' + btoa('lmxretail:lmx#2017'));
this.headers.append('Content-Type', 'application/x-www-form-urlencoded');
Please help any one to apply authentication for my api.
Add Authorization to the CORS Check:
$config['allowed_cors_headers'] = [
'Authorization',
'Origin',
'X-Requested-With',
'Content-Type',
'Accept',
'Access-Control-Request-Method'
];
In order for your preflight request to succeed, the server controller must accept the "Authorization" header as valid. You can do that by adding the "authorization" key along with other allowed headers values:
Access-Control-Allow-Headers: Authorization, Content-Type, Content-Range, Content-Disposition, Content-Description
in php codeigniter backend just put this header in the construct() of your api controller.
example:
class ApiController extends CI_Controller {
function __construct(){
parent::__construct();
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: Origin,X-Requested-With,Content-Type,Accept,Access-Control-Request-Method,Authorization,Cache-Control");
header('Content-Type: application/json');
}
public function index(){
$MYARRAY = array(1);
echo json_encode($MYARRAY);
}
}

Resources