CORS Issue on Ionic CLI 6.13.0 - php

I'm trying to make an http post request in ionic with php on backend,..
Here's my code in ionic :
let body = {
'data': ['data [0]', 'data [1]']
};
let options = {
headers : { 'Content-Type' : 'application/json' }
};
const ifSuccess = (response) => {
console.log(response);
this.data = response;
};
const ifFail = (response) => {
this.error = 'Oops! Une erreur au niveau du serveur...';
};
this.http.post('http://localhost/cantine-itu/test', body, options).subscribe(ifSuccess, ifFail);
Here's the backend (in php flight) :
Flight::before('json', function () {
header('Access-Control-Allow-Origin: http://localhost:8100');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: GET,PUT,POST,DELETE');
header('Access-Control-Allow-Headers: *');
});
Flight::route('POST /test', function(){
$data = Flight::request()->data;
Flight::json($data);
});
I'm getting an error saying that : Access to XMLHttpRequest at 'http://localhost/cantine-itu/test' from origin 'http://localhost:8100' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
(error-image)

Are you getting this error from web browser or a particular device?
Since this is local development and not production I would set to the most permissive possible.
'capacitor://localhost',
'ionic://localhost',
'http://localhost',
'http://localhost:8080',
https://ionicframework.com/docs/troubleshooting/cors

Related

PHP not getting data sent by post from React in Development, whereas Postman works

Given the following code:
fetch(mockproxy+myphp.php,{
method: 'POST',
headers:{'Token':token["token"]},
body: name,
}).then((response) => response.json())
.then((json)=>{
toast.success(JSON.stringify(json));
})
.catch((err) => {
toast.error(JSON.stringify(err));
})
}
mockproxy is helping bypass CORSS. The file looks like this:
const corsAnywhere = require('cors-anywhere');
const express = require('express');
const apicache = require('apicache');
const expressHttpProxy = require('express-http-proxy');
const CORS_PROXY_PORT = 5000;
// Create CORS Anywhere server
corsAnywhere.createServer({}).listen(CORS_PROXY_PORT, () => {
console.log(
`Internal CORS Anywhere server started at port ${CORS_PROXY_PORT}`
);
});
// Create express Cache server
let app = express();
// Register cache middleware for GET and OPTIONS verbs
app.get('/*', cacheMiddleware());
app.options('/*', cacheMiddleware());
// Proxy to CORS server when request misses cache
app.use(expressHttpProxy(`localhost:${CORS_PROXY_PORT}`));
const APP_PORT = process.env.PORT || 5080;
app.listen(APP_PORT, () => {
console.log(`External CORS cache server started at port ${APP_PORT}`);
});
/**
* Construct the caching middleware
*/
function cacheMiddleware() {
const cacheOptions = {
statusCodes: { include: [200] },
defaultDuration: 60000,
appendKey: (req, res) => req.method
};
let cacheMiddleware = apicache.options(cacheOptions).middleware();
return cacheMiddleware;
}
And the server is a shared server where I upload the PHP files so they can access to the DB. The php receives the data and give a response when I use postman but not when I execute the fetch from the dev website, I'm using react, I think it doesn't matter in this case.
The PHP file:
<?php
$headers = apache_request_headers();
header("Access-Control-Allow-Origin: *, ");
header("Access-Control-Allow-Methods: HEAD, GET, POST, PUT, PATCH, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method,Access-Control-Request-Headers, Authorization");
header('Content-Type: application/json');
$method = $_SERVER['REQUEST_METHOD'];
if ($method == "OPTIONS") {
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method,Access-Control-Request-Headers, Authorization");
header("HTTP/1.1 200 OK");
exit;
}
if (isset($_POST["name"])) {
echo json_encode(" name" . $_POST["name"]); //returned on postman
}else{
echo json_encode("no name"); //returned on development.
}
exit;
So this is a code i use when i want to fetch all data from a form. You can obviously not loop through all forms like i do below but just your single form.
// Query all forms in the DOM or a specific one if you want
const forms = document.querySelectorAll('form');
// Loop through them
forms.forEach((form) => {
// if method is post
if (form.method === 'post') {
form.addEventListener('submit', (event) => {
// prevent default submit
event.preventDefault();
// prepare the data
let data = new FormData(form);
// fetch using the form's
fetch(form.action, {
method: 'post',
body: data,
})
// get the text() from the Response object
.then(response => response.text())
.then(text => {
// Display it in the result div
document.getElementById('result').innerHTML = text;
})
}, false);
// if not post (get really)
} else {
form.addEventListener('submit', (event) => {
// prevent default submit
event.preventDefault();
// build the URL query params from the submitted data
const data = new URLSearchParams(new FormData(form).entries());
// Fetch, URL is formed from the action, append ? and then the query params
fetch(form.action + '?' + data)
// get the text() from the Response object
.then(response => response.text())
.then(text => {
// Display it in the result div
document.getElementById('result').innerHTML = text;
})
}, false);
}
});

Connecting PHP Api on server with React expo app localhost. Base url fails

After hours of trying is still can't get my React Expo application (localhost http://192.168.1.113:19006/#/) to connect to my PHP api that is hosted on an external server.
The header of my api file's is as following;
header("Access-Control-Allow-Origin: *");
//header("Access-Control-Allow-Headers: *");
//header("Access-Control-Allow-Credentials: 'true'");
header("Content-Type: application/json");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
When I use postman to connect and test mine /login.php file with the following json body;
POST to: www.URLofAPIlocation.nl/subFolder/api/login.php
{
"email" : "info#email.nl",
"password" : "Password12345"
}
The api returns the JWT token and succes message as expected.
{
"message": "Successful login.",
"jwt": "eyJ0eXA..... ( FULL TOKEN )"
}
But when I try to connect with the following functions within my react native application it try to uses the localhost base url and not the given;
async function postData(url = '', data = {}) {
const response = await fetch(url, {
method: 'POST',
mode: 'cors', // Without cors it fails.
cache: 'no-cache',
// credentials: 'same-origin', // Not sure if needed.
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST',
'Access-Control-Max-Age':' 3600',
},
redirect: 'follow',
referrerPolicy: 'no-referrer',
body: JSON.stringify(data)
});
return await response.json();
}
// https://www.URLofAPIlocation.nl/... and https://URLofAPIlocation.nl/ also not working
function login(){
postData('www.URLofAPIlocation.nl/subFolder/api/login.php', {
email : "info#email.nl",
password : "Password12345",
})
// Other option without error catching. (not working..)
// .then((data) => {
// console.log(data); // JSON data parsed by `response.json()` call
// });
.then(response => {
console.log(response)
return response.json()
})
.then(response => {
console.log("End query"+ response);
return response;
})
.catch(err => {
console.log("Error: "+err)
});
}
I'm not sure what I do wrong since every tutorial and documentation I find the exact same setup as I am using.
The error message is as following;
POST http://192.168.1.17:19006/www.URLofAPIlocation.nl/subFolder/api/login.php 404 (Not Found)
It seems like that react expo uses it's own location as the base url and adds the url of the fetch after it. The location of the api is off course without: http://192.168.1.17:19006//. I can't find where to change or remove this, so help would much be appreciated.
Thanks in advance!
Ps because of personal reasons I've hidden the exact web address of the api location and passwords. The api is hosted on an https domain and functions as expected.

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 send data to laravel using ionic 2

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!!!!

response for preflight is invalid (redirect) error

I am new to Laravel and Lumen framework. I am doing my first project using Lumen. I am trying to create an API calling from angular
Here is my angular code :
app.controller('ListCtrl', ['$scope', '$http', '$location', '$window', function($scope, $http, $location, $window) {
$scope.data = {};
$scope.getdata = function() {
$scope.datas = [];
$headers = {
'Access-Control-Allow-Origin' : '*',
'Access-Control-Allow-Methods' : 'POST, GET, OPTIONS, PUT',
'Content-Type': 'application/json',
'Accept': 'application/json'
};
$http({
url: "http://localhost/service/public/getdata/",
method: "GET",
params: {'place':$scope.data.place,'pincode':$scope.data.pincode},
headers: $headers
})
.success(function(data,status,headers,config) {
$scope.datas=JSON.stringify(data);
console.log($scope.datas);
$scope.navig('/show.html');
})
.error(function(){
alert("failed");
});
};
$scope.navig = function(url) {
$window.location.href = url;
};
}]);
And here is my Lumen route.php :
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
$app->get('/', function () use ($app) {
return $app->version();
});
$app->get('getdata','App\Http\Controllers\PlaceController#index');
And here is PlaceController.php
<?php
namespace App\Http\Controllers;
use App\Places;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class PlaceController extends Controller
{
public function __construct()
{
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
//header("Access-Control-Allow-Origin: http://localhost:8100");
}
public function index()
{
$places = Place::all();
return response()->json($places);
}
}
But it shows "XMLHttpRequest cannot load http://localhost/service/public/getdata/?place=sdfs. Response for preflight is invalid (redirect)" error in console.log.
I have googled for two days,but cant find a solution.
Please help
You might be having problems due to invalid/incorrect Headers in your request. The only type of header that PlaceControllerseems to allow is Content-Type, but you're sending more than that.
Also, Access-Control-Allow-Origin and Access-Control-Allow-Methods headers should be added to the server response for your request, not to the request itself.
From MDN, cross-site requests (which seems to be your case) have to meet the following conditions:
The only allowed methods are:
GET
HEAD
POST
Apart from the headers set automatically by the user agent (e.g. Connection, User-Agent, etc.), the only headers which are allowed to be manually set are:
Accept
Accept-Language
Content-Language
Content-Type
The only allowed values for the Content-Type header are:
application/x-www-form-urlencoded
multipart/form-data
text/plain
Note: I never worked with Laravel or Lumen, but in my case if I don't set the headers correctly I end up with the same response for preflight is invalid (redirect) error.

Categories