Angular 2+ and Laravel - Internal Server Error - laravel

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());
}

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

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

Vue + Laravel + tinymce upload image blocked by CORS policy

I want to upload images insinde the TinyMCE editor but i has been blocked by CORS policy.
I had setting the CORS on my Laravel project. Other function is OK to get the data from this Laravel project
These are my Javascript settings:
uploadImg(blobInfo, success, failure) {
let formData = new FormData();
formData.append("file", blobInfo.blob(), blobInfo.filename());
this.axios({
method: "post",
url: "/test2",
headers: {
"Content-Type": "multipart/form-data"
},
withCredentials: false,
data: formData
}).then(res => {
console.log(res.data);
});
}
These are my CORS settings:
public function handle(Request $request, \Closure $next)
{
$this->headers = [
'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE',
'Access-Control-Allow-Headers' => $request->header('Access-Control-Request-Headers'),
'Access-Control-Allow-Credentials' => 'true',
'Access-Control-Max-Age' => 1728000
];
$this->allow_origin = [
'http://localhost',
'http://localhost:8080',
'http://localhost:8000',
];
$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
if (!in_array($origin, $this->allow_origin) && !empty($origin)){
return new Response('Forbidden', 403);
}
if ($request->isMethod('options'))
return $this->setCorsHeaders(new Response('OK', 200), $origin);
$response = $next($request);
$methodVariable = array($response, 'header');
if (is_callable($methodVariable, false, $callable_name)) {
return $this->setCorsHeaders($response, $origin);
}
return $response;
}
/**
* #param $response
* #return mixed
*/
public function setCorsHeaders($response, $origin)
{
foreach ($this->headers as $key => $value) {
$response->header($key, $value);
}
if (in_array($origin, $this->allow_origin)) {
$response->header('Access-Control-Allow-Origin', $origin);
} else {
$response->header('Access-Control-Allow-Origin', '');
}
return $response;
}
this is the error message:
error message
Can anyone tell me where did i make a mistake? Thanks
You could start Chrome or chromium with cors policy disabled.
This would be helpful for debugging
check this answer on how to do that here
check ths answer on how to do it in laravel here

No 'Access-Control-Allow-Origin' header is present on the requested resource - Ionic 3 and Laravel

I am trying to connect my application with a backend server in Laravel
I have an interceptor that adds the headers in the request:
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log('----------------- SESSION -----------------');
console.log(this.session.token);
this.token = this.session.token;
const headers = this.buildRequestHeaders();
const authRequest = req.clone({
setHeaders: {
'Access-Control-Allow-Credentials': 'false',
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Content-Type",
"Access-Control-Allow-Methods": "OPTIONS,POST,GET",
'Authorization': `Bearer ${this.token}`
}
});
return next.handle(authRequest);
}
On the server I have a middleware:
<?php
namespace App\Http\Middleware;
use App\Helpers\JsonResponseHelper;
use Closure;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Middleware\GetUserFromToken;
class JwtCheck extends GetUserFromToken
{
public function handle($request, Closure $next)
{
header('Content-Type', 'application/json');
header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Request-Headers', 'Origin, Authorization, Content-Type, Accept');
header('Access-Control-Allow-Origin', '*');
if (strpos($request->headers->get("Authorization"), "Bearer ") === false) {
$request->headers->set("Authorization", "Bearer " . $request->headers->get("Authorization"));
}
if (!$token = $this->auth->setRequest($request)->getToken()) {
$data['errors'] = trans('auth.failed');
$message = trans('auth.failed');
return JsonResponseHelper::dataResponse(trans('messages.error'), $data, true, 401, $message);
}
try {
//$user = $this->auth->authenticate($token);
$user = JWTAuth::parseToken()->authenticate($token);
} catch (TokenExpiredException $e) {
$data['errors'] = trans('messages.token-expired');
$message = trans('messages.token-expired');
return JsonResponseHelper::dataResponse(trans('messages.error'), $data, true, 401, $message);
} catch (JWTException $e) {
$data['errors'] = $e->getMessage();
$message = trans('messages.error');
return JsonResponseHelper::dataResponse(trans('messages.error'), $data, true, 401, $message);
} catch (TokenInvalidException $e) {
$data['errors'] = $e->getMessage();
$message = trans('messages.error');
return JsonResponseHelper::dataResponse(trans('messages.error'), $data, true, 401, $message);
} catch (Exception $e) {
$data['errors'] = $e->getMessage();
$message = trans('messages.error');
return JsonResponseHelper::dataResponse(trans('messages.error'), $data, true, 401, $message);
}
if (!$user) {
$data['errors'] = trans('auth.failed');
$message = trans('auth.failed');
return JsonResponseHelper::dataResponse(trans('messages.error'), $data, true, 401, $message);
}
$request->merge(array("user" => $user));
$request->merge(array("token" => $token));
return $next($request);
Here's my problem:
https://i.stack.imgur.com/CG9Tq.png
This is the request sent to the server. Apparently my Access-Control-Allow-Originis adding inside the Request headers:
https://i.stack.imgur.com/WXN0L.png
If you see the error states Response to Pre-flight request doesn't pass the control check, At this control check the server tells the browser or client, that it is allowed to make request to it. This Request is fired before your original the original request. You are setting headers in the controller, the request gets rejected before it reaches the controller,
Create a middleware named Cors and in its handle method:
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, x-requested-with');
}
and in Kernel.php pass your newly created middleware.
protected $middleware = [
\App\Http\Middleware\Cors::class,
];
you don't need to pass access-control headers in your ionic client, these are generated by your server during preflight, to let the client know what is allowed by the server.
Set headers in your ionic like,
setHeaders: {
Accept: `application/json`,
'Content-Type': `application/json`,
Authorization: `Bearer ${this.token}`
}
Also JWT-Auth comes with a inbuilt middleware to check if the request is by an authenticated entity, simply use it on your protected routes
jwt.auth = \Tymon\JWTAuth\Middlware\GetUserFromToken::class

Resources