Vue + Laravel + tinymce upload image blocked by CORS policy - laravel

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

Related

How to solve SyntaxError: Unexpected token < in JSON at position 0 in Paypal checkout in Laravel

I am doing Paypal integration in Laravel. I have used composer require srmklive/paypal to install the srmklive/paypal package in this project.
When I press the PayPal button, I get this error:
Here is my code:
code from blade file:
paypal.Buttons({
createOrder: function(data, actions) {
return fetch('api/paypal/order/create/', {
method: 'post',
body:JSON.stringify({
"value":100
})
}).then(function(res) {
return res.json();
}).then(function(orderData) {
return orderData.id;
});
},
onApprove: function(data, actions) {
return fetch('/api/paypal/order/capture/', {
method: 'post',
body: JSON.stringify({
orderID: data.orderID
})
}).then(function(res) {
return res.json();
}).then(function(orderData) {
var errorDetail = Array.isArray(orderData.details) && orderData.details[0];
if (errorDetail && errorDetail.issue === 'INSTRUMENT_DECLINED') {
return actions.restart();
}
if (errorDetail) {
var msg = 'Sorry, your transaction could not be processed.';
return alert(msg); // Show a failure message (try to avoid alerts in production environments)
}
});
}
}).render('#paypal-button-container');
code from paymentController:
class PaymentController extends Controller
{
public function create(Request $request){
$data = json_decode($request->getContent(), true);
$provider = \PayPal::setProvider();
$provider->setApiCredentials(config('paypal'));
$token = $provider->getAccessToken();
$provider->setAccessToken($token);
$price = Plan::getSubscriptionPrice($data['value']);
$description = Plan::getSubscriptionDescription($data['value']);
$order = $provider->createOrder([
"intent" => "CAPTURE",
"purchase_units" => [
[
"amount" => [
"currency_code" => "USD",
"value" => $price
],
"description" => $description
]
]
]);
return response()->json($order);
}
public function capture(Request $request) {
$data = json_decode($request->getContent(), true);
$orderId = $data['orderID'];
$provider = \PayPal::setProvider();
$provider->setApiCredentials(config('paypal'));
$token = $provider->getAccessToken();
$provider->setAccessToken($token);
$result = $provider->capturePaymentOrder($orderId);
return response()->json($result);
}
}
How can I solve this error?
The route api/paypal/order/create/ is returning/outputting text that is not JSON, such as an HTML error page or something else that begins with an HTML tag.
The route must only output JSON, and must contain a valid id from the PayPal API.

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

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

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

Ajax successful when laravel authentication fails

I have a problem I have two forms on regular form and one ajax processed form. The regular form works as needed but the ajax form passes as successful even when authentication of the server side fells.
My loginHandler function is below
public function handleLogin(Request $request) {
// init auth boolean to false
$auth = false;
// run validation rules
$validator = User::validation($request->all(), User::$login_validation_rules, User::$login_error_messages);
// get credentials
$credentials = $request->only('email','password');
if($validator->fails()) {
return back()
->withErrors($validator)
->withInput();
}
$credentials = array_merge($credentials,['activated' => 1]);
// get remember from request
$remember = $request->has('remember');
if (\Auth::attempt($credentials, $remember)) {
$auth = true;
}
if($request->ajax()) {
$response = response()->json([
'auth' => $auth,
'intended' => \URL::route('home')
]);
return $response;
}
return redirect()->intended('/');
}
My ajax code is this
$('#login-nav').validate({
rules : {
email : {
required : true,
email : true
},
password : {
required : true
}
},
messages : {
email : {
required : '<div class="alert-danger alert-validation">Email is a required field.</div>',
email : '<div class="alert-danger alert-validation">Please enter a valid Email.</div>'
},
password : {
required : '<div class="alert-danger alert-validation">Password is a required field.</div>'
}
},
submitHandler: function (form){
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('value')
},
type: $(form).attr('method'),
url: $(form).attr('action'),
data: $(form).serialize(),
dataType: 'json',
success: function (data) {
var html = '<div class="alert alert-success">Login Successful</div>';
$('#loginMsg').html(html);
return window.location = '/';
},
error: function (data) {
var html = '<div class="alert alert-danger">Email/Password is invalid</div>';
$('#loginMsg').html(html);
}
});
return false;
}
I would like to have the same behavior as my regular non ajax form. but instead of going to error in my ajax it's going to success. Any help would be greatly appreciated.
Auth::attempt will return you true or false, by default if you return a response()->json() without the 2nd parameter, it will be default to 200 (success). So based on the Auth::attempt you should either return 400 if it fails to login, then it should go into your ajax's error function.
$auth = \Auth::attempt($credentials, $remember);
if($request->ajax()) {
$responseCode = 200;
if( ! $auth) {
$responseCode = 400;
}
$response = response()->json([
'auth' => $auth,
'intended' => \URL::route('home')
], $responseCode);
return $response;
}

Resources