This is propably something simple and obvious but I can't see where the problem is. After some research I found that in order to enable CORS in laravel 4 oen should add the following to the filters.php:
App::before(function($request)
{
if($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
$statusCode = 204;
$headers = [
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers' => 'Origin, Content-Type, Accept, Authorization, X-Requested-With',
'Access-Control-Allow-Credentials' => 'true'
];
return Response::make(null, $statusCode, $headers);
}
});
App::after(function($request, $response)
{
$response->headers->set('Access-Control-Allow-Origin', '*');
$response->headers->set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
$response->headers->set('Access-Control-Allow-Headers', 'Origin, Content-Type, Accept, Authorization, X-Requested-With');
$response->headers->set('Access-Control-Allow-Credentials', 'true');
return $response;
});
So to my mind when one does this in angularjs:
app.factory('RestFactory', function ($http) {
var BASE_URL = 'url_to_the_site';
return {
get: function (target) {
return $http({method: 'GET', url: BASE_URL + target});
},
post: function (target, data) {
return $http.post(BASE_URL + target, data);
}
};
});
It should work right? When running Laravel 4 in localhost:8000 at development mode it seems to work. However when I transfer the Laravel to my site and try accessing the site url all I get is:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
So What am I doing wrong here? It works on local, the BASE_URL also works when going to the url with a browser so what am I missing here?
Related
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
Facing CORS in angular, when i was trying to make a API call between my localhost to another domain.I am getting 404 issue .
1.Front End : Angualr 7
Front end request part:
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': 'true',
'Access-Control-Allow-Methods':'POST',
'Access-Control-Allow-Headers': 'Content-Type'
})
}
login(username: string, password: string) {
return this.http.post<any>('http://remote/djaxtesting/enter_uiupgrade/index.php/api/v1/user/validate',
{acc_type: "ADMIN", uemail: "djax_admin#dreamajax.com", upw: "123456"},httpOptions)
.pipe(map(user => {}))
}
Back end coding :
<?php defined('BASEPATH') OR exit('No direct script access allowed');
header ("Access-Control-Allow-Origin: *");
header ("Access-Control-Allow-Credentials: true");
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');
header('Content-Type: application/json');
public function validate_post()
{
$role = array('ADVERTISER','TRAFFICKER','ADMIN','MANAGER');
if($this->post('acc_type') !='' and in_array($this->post('acc_type'),$role))
{
switch(strtoupper($this->post('acc_type')))
{
case "ADMIN":
$adminObj = $this->do_networks->validate_user($this->post('uemail'),$this->post('upw'),$this->post('acc_type'));
//$this->response($adminObj, 200);
}
}
}
enter image description here
We using php for api. Helping handing needs to solve this issue ?
The problem with the option method. Option request should be a 200 returning an empty response. Then the browser will send the real POST request.
for that replace with the headers in your PHP File in the constructor. It will work.
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Authorization");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
$method = $_SERVER['REQUEST_METHOD'];
if ($method == "OPTIONS") {
die();
}
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.
I am working on a Hybrid application I want to sent json data to laravel php server using Ionic 2.
I am continuously getting error as
XMLHttpRequest cannot load http://192.168.0.101:8000/SaveUsers.
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:8100' is therefore not allowed
access.
Ionic Code:
register-recipient-page.ts
this.registrationService.sendData(this.donarDetails,this.recipientDetails).subscribe(
response => console.log(response), // success
error => console.log(error), // error
() => console.log('completed') // complete
);
Ionic Code:
registration.service.ts
sendData(recipient,donar): Observable<Object> {
let encoded_data = JSON.stringify({recipientDetails:recipient, donarDetails:donar});
let headers = new Headers();
headers.append('Content-Type', 'application/json;charset=utf-8');
headers.append('Access-Control-Allow-Origin', '*');
headers.append('Access-Control-Allow-Methods', 'GET, POST, PUT,DELETE, OPTIONS');
//let headers = new Headers({ 'Content-Type': 'application/json;charset=utf-8' });
let options = new RequestOptions({ headers: headers });
console.log(encoded_data);
return this.http.post( 'http://192.168.0.101:8000/SaveUsers',encoded_data, options).map(
(res: Response) => res.json() || {}
);
}
laravel: web.php
Route::group(['middleware' => 'cors'], function(){
Route::get('/SaveUsers', 'UserController#saveUser');
});
Cors.php
public function handle($request, Closure $next){
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT,DELETE, OPTIONS');
}
I tried to do testing using simple get on the same url without sending any data, it was working fine.
Please help!!!!
I use SlimFramework
When i run my script locali with xampp it works fine.
But i uploaded the script to the server and now it cone the error that the header was not set.
XHR does not allow payloads for GET request.
or change a method definition in settings.
Here the script in angular
$rootScope.globals = $cookies.getObject('globals') || {};
if ($rootScope.globals.currentUser) {
$http.defaults.headers.common['Authorization'] = 'Basic ' + $rootScope.globals.currentUser.token;
}
$rootScope.$on('$locationChangeStart', function (event, next, current) {
var restrictedPage = $.inArray($location.path(), ['/login', '/register', '/password']) === -1;
var loggedIn = $rootScope.globals.currentUser;
if (restrictedPage) {
if (!loggedIn) {
$location.path('/login');
} else {
UserService.checkToken($rootScope.globals.currentUser.token)
.then(function (response) {
if (!response.success) {
$location.path('/login');
}
});
}
}
});
function checkToken(token) {
return $http.get('api/v1/token').then(handleCallback, handleCallback);
}
function handleCallback(res) {
console.log(res);
return res.data;
}
And here the script with SlimFramework
$config['displayErrorDetails'] = true;
$config['addContentLengthHeader'] = false;
$config['determineRouteBeforeAppMiddleware'] = true;
$app = new \Slim\App(["settings" => $config]);
$container = $app->getContainer();
// This is the middleware
// It will add the Access-Control-Allow-Methods header to every request
$app->add(function ($req, $res, $next) {
$response = $next($req, $res);
return $response
->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');
});
$app->get('/token', function ($request, $response){
$token = $request->getHeaderLine('Authorization');
if($token){
$db = new DbOperation();
if($db->checkAuthentication($token)){
$return = $response->withJson(["success"=> true], 200);
} else {
$return = $response->withJson([
"success"=> false,
"message"=>'Invalid token'
], 403);
}
} else {
$return = $response->withJson([
"success"=> false,
"message"=>'Header not set.'
], 403);
}
return $return;
});
Whats my Problem?
Everyone knows?
Thx
UPDATE:
Get request
The response from API testing
HTTP/1.1 403 Forbidden
Server: nginx
Date: Mon, 27 Mar 2017 11:57:27 GMT
Content-Type: application/json;charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
X-Powered-By: PHP/5.6.30
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: X-Requested-With, Content-Type, Accept, Origin, Authorization
Access-Control-Allow-Methods: GET
X-Powered-By: PleskLin
if you want to open the api to cors call to every possible origin(test only) try this:
$app->add(function ($req, $res, $next) {
$response = $next($req, $res);
return $response
->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');
});
Or there is this Middleware that do the same: https://github.com/palanik/CorsSlim
If you are not sure what is the header name generated by NG, you can debug the header sent to SLIM. In SLIM, it can be done like this:
$headers = $request->getHeaders();
foreach ($headers as $name => $values) {
echo $name . ": " . implode(", ", $values);
}
Im using jquery, I set token in header globally, like this:
$.ajaxPrefilter(function( options, oriOptions, jqXHR ) {
jqXHR.setRequestHeader("Authorization", sessionStorage.token);
});
That will send a token with a header name:
HTTP_AUTHORIZATION
To get specific header variable:
$token_array = $request->getHeader('HTTP_AUTHORIZATION');
if (count($token_array) == 0) {
$data = Array(
"jwt_status" => "token_not_exist"
);
return $response->withJson($data, 401)
->withHeader('Content-type', 'application/json');
}
$token = $token_array[0];