Cors not apply in laravel5.2 - php

Cors working in this api users/login problem in postjob/store api i solved this issue adding cors true in angular.
After few days i call this api again same error occur
XMLHttpRequest cannot load http://192.168.10.5/jobpost1/public/api/job. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9001' is therefore not allowed access.
Routes.php
Route::group(['prefix' => 'api'], function () {
Route::post('users/login', array('middleware' => 'Cors', 'uses' => 'Auth\AuthController#login'));
});`
Route::group(['prefix'=>'api'], function()
{
Route::group(['middleware'=>'jwt-auth'], function ()
{
Route::post('postjob/store', array('middleware' => 'Cors', 'uses'=> 'PostController#store'));
});
});
Cors.php
class Cors
{
public function handle($request, Closure $next)
{
// ALLOW OPTIONS METHOD
$headers = [
'Access-Control-Allow-Origin'=> '*',
'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin',
'Access-Control-Allow-Credentials' => 'true'
];
if($request->getMethod() == "OPTIONS") {
// The client-side application can set only headers allowed in Access-Control-Allow-Headers
return Response::make('OK', 200, $headers);
}
$response = $next($request);
foreach($headers as $key => $value)
$response->header($key, $value);
return $response;
}
angular code
return $http({
method: 'POST',
url: 'http://192.168.10.4/jobpost1/public/api/job',
cors: true,
xhrFields: {
withCredentials: true
},
params: {
"token" :token,
"user_id": userId,
"job_shift": job_shift,
"job_type": job_type,
"job_description":job_description,
"degree_title": degree_title,
"city": city,
"experience": experience,
"career_level": career_level,
"gender":gender,
"total_position": total_position,
"minimum_edu":minimum_edu,
"apply_before": apply_before
}
}).then(function successCallback(response, status) {
callback(response, status);
debugger;
}
, function errorCallback(response, status) {
callback(response, status);
debugger;
});
};

Rather than adding headers using foreach:
foreach($headers as $key => $value)
$response->header($key, $value);
Give this a go instead:
$response->headers->add($headers);

Related

Calling a laravel route from a different Domain

Let's say I have a next js application which exists in a different domain that needs to call a laravel route. This route leads to a login page.
This is what I did on react side
const handleSubmit = async (e) => {
e.preventDefault();
try {
const result = await axios.get("http://localhost:5001/login", {
headers: {
// "content-type": "application/json",
"x-api-signature": "my-secret-token",
},
});
console.log(result);
} catch (error) {
console.log(error);
}
};
I am getting cors error on front end
// In Laravel auth.php
Route::get('login', [AuthenticatedSessionController::class, 'create'])
->name('login');
This route leads to a simple login page.
You can use CORS Middleware for Laravel
Or by using middleware, something like (not tested)
Note that https://stackoverflow.com should be your app domain.
class Cors
{
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', 'https://stackoverflow.com')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, X-Token-Auth, Authorization');
}
}
Read
Laravel CORS Guide: What It Is and How to Enable It

CORS policy laravel vueJS

I have a problem with CORS in laravel and vueJS. i need send parameter to other website with my aplication in laravel, but always return error CORS. I tried create a middleware but i don´t know how i implements my routes with this.
i´m tried add header in index.php to Laravel, returned CORS, i´m tied add this code in petetition axios
let url = "/contrarBono30Min";
let bono = "Bono30Min";
axios.defaults.headers.common['Access-Control-Allow-Origin'] = '*';
axios.post(url, {
bono: bono,
token: csrf_token,
}
)
My Controller
public function contrarBono30MinHome(Request $request){
$usuario = \Auth::user()->id;
$bono = $request["bono"];
$precioBono = \DB::select("SELECT precio FROM bonos WHERE codBono = '1'");
return redirect('.....URL?bono='.$bono.'&user='.\Auth::user()->nombre.'&nif='.\Auth::user()->nif.'&precio='.$precioBono[0]->precio);
}
action button
contratar: function(){
$(".contratar").on("click", function(e){
var bono = $(this).closest("tr").find("td:eq(0)").text();
var csrf_token = $('meta[name="csrf-token"]').attr('content');
if(bono == 1){
let url = "/contrarBono30Min";
let bono = "Bono30Min";
axios({
method: 'POST',
url: url,
data: {
bono
}
});
}
if(bono == 2){
let url = "/contrarBono1H";
axios.post(url, {bono:Bono1H})
.then((response) => {
console.log(response);
});
}
if(bono == 3){
let url = "/contrarBono5h";
axios.post(url, {bono:Bono5H})
.then((response) => {
console.log(response);
});
}
if(bono == 4){
let url = "/contrarBono10H";
axios.post(url, {bono:Bono10H})
.then((response) => {
console.log(response);
});
}
if(bono == 5){
let url = "/contrarBono24H";
axios.post(url, {bono:Bono24H})
.then((response) => {
console.log(response);
});
}
});
nothing, return CORS...
my URL in axios is external, i need to send info to other web, how pad type, price, name buyers, etc... But redirect i have a CORS ERROR
i don´t know how resolve this problem.
thanks for help
CORS FILE
<?php
return [
/*
|--------------------------------------------------------------------------
| Cross-Origin Resource Sharing (CORS) Configuration
|--------------------------------------------------------------------------
|
| Here you may configure your settings for cross-origin resource sharing
| or "CORS". This determines what cross-origin operations may execute
| in web browsers. You are free to adjust these settings as needed.
|
| To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
|
*/
'paths' => ['api/*'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => false,
];
put these lines inside your public/index.php, this is the easiest way.
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');

Get {"message":"Unauthenticated."} when sending POST request to laravel server

I have a problem with sending POST request from Vue axios to laravel server with sanctum.
Firstly I'm getting token.
My route of api.php
Route::post('/get_token', function (Request $request) {
$request->validate([
'email' => 'required|email',
'password' => 'required',
'device_name' => 'required'
]);
$user = User::where('email', $request->email)->first();
if (! $user || ! Hash::check($request->password, $user->password)) {
throw ValidationException::withMessages([
'email' => ['The provided credentials are incorrect.'],
]);
}
return $user->createToken($request->device_name)->plainTextToken;
});
vue axios
this.$axios.post('/api/get_token', {
email: this.email,
password: this.password,
device_name: this.device_name,
}).then(response=>{...});
And when I send GET request with received token, it works correctly
vue axios
this.$axios.get('/api/book/all', {
headers: {
"Authorization": 'Bearer ' + this.$store.getters.getToken
}
}).then(response=>{...})
api.php
Route::middleware('auth:sanctum')->get('/book/all', 'BookController#all');
But when I try to send POST request, I get {"message":"Unauthenticated."} and 401 error
vue axios
this.$axios.post('/api/book/add', {
headers: {
"Authorization": 'Bearer ' + this.$store.getters.getToken,
},
data: {
title: this.addingTitle,
author: this.addingAuthor,
}
})
api.php
Route::middleware('auth:sanctum')->post('/book/add', 'BookController#add');
Sorry, I’m just a noob in web and don’t understand many things, hope you can help me.
If you use post then the 1st parameter is the URL and the 2nd one is the data your are posting. In your case it might make more sense to use:
this.$axios({
method: 'POST',
url: '/api/book/add'
headers: {
"Authorization": 'Bearer ' + this.$store.getters.getToken,
},
data: {
title: this.addingTitle,
author: this.addingAuthor,
}
})
or if you want to still use .post then:
this.$axios.post('/api/book/add', {
title: this.addingTitle,
author: this.addingAuthor,
}, {
headers: {
"Authorization": 'Bearer ' + this.$store.getters.getToken,
}
})

Request blocked by CORS policy

I have an API built with PHP Slim Framework 3 and testing the API with Postman everything is working great but when I put the app on the server and tried to make an Ajax Call I've got this message:
Failed to load https://api.mydomain.net/usuario/autenticar?xAuthClienteID=2&xAuthChaveApi=3851b1ae73ca0ca6e3c24a0256a80ace&login=admin&senha=teste: Redirect from 'https://api.maydomain.net/usuario/autenticar?xAuthClienteID=2&xAuthChaveApi=3851b1ae73ca0ca6e3c24a0256a80ace&login=admin&senha=teste' to 'https://api.mydomain.net/404.html' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
I've looked up Slim docs on how to enable CORS on my server and applied it on the function I use to return JSON. It looks like this:
public function withCustomJson($meta = null, $data = null)
{
if (isset($data)) {
$finalResponse['data'] = $data;
}
$finalResponse['meta'] = array(
'status' => (isset($meta['status']) ? $meta['status'] : null),
'message' => (isset($meta['message']) ? mb_convert_encoding($meta['message'], "UTF-8", "auto") : null)
);
$response = $this->withBody(new Body(fopen('php://temp', 'r+')));
$response->body->write($json = json_encode($finalResponse));
// Ensure that the json encoding passed successfully
if ($json === false) {
throw new \RuntimeException(json_last_error_msg(), json_last_error());
}
//Allowing CORS as Slim docs states
$responseWithJson = $response->withHeader('Content-Type', 'application/json;charset=utf-8')
->withHeader('Access-Control-Allow-Origin', '*')
->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
if (isset($meta['codStatus'])) {
return $responseWithJson->withStatus($meta['codStatus']);
}
return $responseWithJson;
}
And here's what my Ajax call looks like:
<script type="text/javascript">
try {
$.ajax({
url: 'https://api.mydomain.net/usuario/autenticar',
type: 'GET',
dataType: 'json',
data: {
xAuthClienteID:'2',
xAuthChaveApi: '3851b1ae73ca0ca6e3c24a0256a80ace',
login: 'admin',
senha: 'teste'
},
ContentType: 'application/json',
success: function(response){
console.log(response);
},
error: function(err){
console.log(err);
}
});
}
catch(err) {
alert(err);
}
</script>
So, what am I doing wrong? Appreciate any help.

Unable to get input data sent from cross site domain

I am using laravel as backend and angujarjs as frontend to make an application. The frontend is sitting in another server, and therefore I have to deal with cross domain policy. I have enabled CORS, so I can "send" post request.
The problem is that when I am trying to get Input::all() in laravel, the request gets cancelled. (status shown 'cancelled' in Chrome network). But when I dont use Input, everything is OK.
//laravel
class SessionController extends BaseController {
protected $entity;
public function __construct(SessionEntity $entity)
{
$this->entity = $entity;
}
public function getLogin()
{
return Response::json('hello')->header('Access-Control-Allow-Origin', '*');
}
public function postLogin()
{
//$data = Input::all();
//return Response::json($data);
// $user = $entity->login($data);
// if($user)
// {
// return Response::json($user);
// } else {
// return Response::json($entity->errors(), 400);
// }
//the code below is OK (able to send response back) , but the code above is not, because I am using Input::all()
$data = array(
"email" => "324234",
"password" => "654321"
);
return Response::json($data);
}
}
//angularjs
.controller('LoginController', ['$scope', '$http', function($scope, $http) {
$scope.send = function(credential) {
$http({
method: 'POST',
url: 'http://localhost:8000/api/session/login',
data: credential,
headers: {
'Content-Type': 'application/json; charset=UTF-8'
}
})
.success(function(data, status, headers) {
console.log(data);
console.log(status);
console.log(headers);
});
};
}]);
Here's the headers to enable CORS
App::after(function($request, $response)
{
$response->headers->set('Access-Control-Allow-Origin', '*');
$response->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT');
$response->headers->set('Access-Control-Allow-Headers', 'Content-Type');
$response->headers->set('Access-Control-Allow-Credentials', 'true');
$response->headers->set('Access-Control-Max-Age', '1728000');
$response->headers->set('Content-Type', 'application/json; charset=UTF-8');
return $response;
});
What did I miss??
I found it. I use namespace but didn't include 'use Input'.
silly me...
Also, I found that I have to explicitly set Content-Type to 'application/json' in order to receive data using Input::all() in laravel, otherwise I get no data.
For cross domain requests you must use jsonp instead json

Categories