CORS issue on same domain Ajax/PHP - php

I'm facing a CORS problem with an ajax call.
I have a php file called through ajax with the following headers
header('Access-Control-Allow-Origin: * ');
header('Access-Control-Allow-Methods: GET, ADD, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: *'); // also tested with Content-Type, x-requested-with
There is no error when the file is called from
http://www.mywebsite.com
but it throws a 403 forbidden error when it's called from
https://mywebsite.com
https://www.mywebsite.com
To be more specific the GET is ok, but the ADD is not allowed.
As we're talking about the same domain, i don't understand why there's a '403' error
Thanks for your help,

what php framework
if this is laravel you are using make sure you see the file config/cors.php
or the file VerifyCsrfToken
protected $except = [
'*'
];

Related

Getting error like Response to preflight request doesn't pass access control check

I am doing Laravel project. In this I have folder name as onlinebookingmanager in localhost. And I run a command like npm run dev. After this I run the url http://localhost:8080/admin/login. Now i am getting error like
Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'http://localhost' that is not equal to the supplied origin. Origin 'http://localhost:8080' is therefore not allowed access.
I have installed plugin CORS but it seems doesn't working.
This issue due to missing header attribute Access-Control-Allow-Origin which should be *.
Best way to resolve this issue is integrate the following library to your laravel project
https://github.com/barryvdh/laravel-cors
This library provides CORS solution in middleware so in every request you will get perfect header.
Have you included following code in your app.js
var cors = require('cors')
var app = express();
app.use(cors());
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type,
Accept");
next();
});
Hope it helps.

Preflight response is not successful with proper headers

I'm having issue getting my ionic app to POST to my API. On my api I have set the following headers:
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Allow-Methods: GET,PUT,POST,DELETE,OPTIONS");
When posting from Postman or the actual website, everything functions as expected and I see these headers come back but once I open up my app and send a request, it no longer works.
GET Requests are working fine, it's just POST requests that are broken. I use the following to send a post request on my app:
/**
* Post to the API
* #param path Where to go
* #param params What to send
*/
private post(path, params): Promise<any> {
return this.http
.post(this.apiUrl + path, params)
.toPromise()
.then(r => r.json());
}
I get the following error inside of my ionic app
Failed to load resource: Preflight response is not successful
XMLHttpRequest cannot load https://mmcalc.com/api/calculate. Preflight response is not successful
I've been pulling my hair out over this for nearly 15 hours now, I don't understand why it won't work.
This issue happened due to the WKWebView Mostly
So, the very simple way to use the WKWebView in Ionic is that You Must uninstall the previously installed UIWebView from the plugin by running the following command.
ionic cordova plugin remove cordova-plugin-ionic-webview
After that try to add the WKWebView Plugin with this command
ionic cordova plugin add cordova-plugin-wkwebview-engine
When the WkWebView plugin is installed the very next thing is to add the following lines in the config.xml file
feature name="CDVWKWebViewEngine"
param name="ios-package" value="CDVWKWebViewEngine"
feature
preference name="CordovaWebViewEngine" value="CDVWKWebViewEngine"
preference name="WKWebViewOnly" value="true"
After doing all that when you try to run the application and hit some api call you will get the preflight issue in that due to CORS so to fix that. Simply run the following command
ionic cordova plugin add cordova-plugin-wkwebviewxhrfix
After adding the above plugin the CORS issue will be resolved
Thanks,
Happy Coding
If you're only having the issue in iOS then it sounds like an issue with WKWebView
https://ionicframework.com/docs/wkwebview/
When the server receives the OPTIONS request, what does it respond with?
I would make sure the response from the OPTIONS request contains the headers WKWEBView is expecting, otherwise it will prevent the code from the making the call.
The solution was very simple but not very obvious, I simply had to set the proper headers on my API. This article solved the issue for me and was very simple.
# Always set these headers.
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header always set Access-Control-Max-Age "1000"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"
# Added a rewrite to respond with a 200 SUCCESS on every OPTIONS request.
RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]
the preflight request uses the OPTIONS request method. You should make sure that your API endpoint returns a successful status code for the OPTIONS request method and the response should also include the CORS headers which you have mentioned above. GET requests are probably working because they dont need a prefligh request. I would guess that in your case the OPTIONS method returns a wrong status code.

Laravel 5.4 Route::post() NotFoundException

Hi I have a problem with Laravel 5.4 routes, Route::get() are working but Route::post() give me NotFoundException error back.
Take a look at login route in api.php this one is for sure not working but was working before I started using Homestead and vagrant.
Any ideas ? Here are my interresting configurations about API and routes (Hosted files on github) :
1) RouteServiceProvider.php
2) api.php
3) Kernel.php
Can't understand why ! If needed I can upload full project but I can't stand why it doesn't work since start of the week.
Please be kind with me this is my first project with Laravel.
Kind regards
Edit : Just added php artisan route:list --path:foobar result :
route-list-ouptut
Your code seems fine, except I would remove these lines from api.php:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
As I understand these are request headers. So you should add the in your Postman request headers (or another Rest client). And not in any where in your code.
If you want to add headers to response, rather then request here are Laravel Create Response Docs

IONIC Content-Type is not allowed by Access-Control-Allow-Headers

I was working on an angularJS, IONIC project with CI backend.
I was sending parameters to the server using POST Method, and receiving it using the CodeIgniter Input class and everything was working OK.
Now that app going to be native Android, the developer should send parameters as JSON array. So I changed my backend API function to receive it like:
$data = json_decode(file_get_contents('php://input'), true);
$email = $data->email;
It works great but the problem now is when I try to access the function using IONIC app I get an php error.
XMLHttpRequest cannot load
http://192.168.1.122/project/index.php/api/login.
Request header field Content-Type is not allowed by Access-Control-Allow-Headers.
on my API I allowed all CORS
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT');
...But I still get the same error.
Can I get any other solution around this point.
Thanks for your help.
You have to add cordova-plugin-whitelist plugin to implements a whitelist policy for navigating the application webview on Cordova 4.0
ionic plugin add cordova-plugin-whitelist
then
ionic build <platform>
Source

Connect to Homebrew PHP/MySQL from Angular App using $http

I am building an Angular App with Gulp locally on my dev machine, that will eventually be a SaaS. All the data is hardcoded JSON in a service purely to get the front-end working.
Now I am ready to connect to a local database and will use PHP/MySQL.
I have a local development environment on OSX setup with Homebrew that has PHP and MySQL ready to go.
The issue:
I get a 404 when I use the url: 'db-insert.php' line no matter where I put the db-insert.php file in my directory structure.
POST http://localhost:3000/db-insert.php 404 (Not Found)
var request = $http({
method: 'post',
url: 'db-insert.php',
data: {
name: $scope.name,
email: $scope.email,
message: $scope.message
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
I have investigated
• CORS: Tried open -a 'Google Chrome' --args -allow-file-access-from-files
• gulp-connect-php
• gulp-webapp-running-browsersync-and-php
• BrowserSync Proxies
The app uses Gulps BrowserSync which has a proxy option that leverages Express to connect to a defined middleware, but I am stumped at where to point it or if it is the correct option at all.
Any explanation of what the correct way to do this is would be great. I think the answer is probably a combination of what I have found, but the implementation is the issue. Thanks much.
Ok, This turned out to be a filesystem/CORS issue. Here is how I solved it:
1) Go through the server to get to the php file
http://127.0.0.1/dev/db-insert.php
NOT
file://myproject/dev/db-insert.php
I was trying to access the file directly in the file system and not by its URL on the PHP server I have running as my localhost. When I changed the url to go through the apache server to find the file, it was able find it.
2) Once I got to the file I got the CORS issue
Adding the code below to the top of db-insert.php executes allowed the file to be accessed.The server could then execute the code.
header('Access-Control-Allow-Origin: '. $_SERVER['HTTP_ORIGIN'] );
header('Access-Control-Allow-Credentials: true' );
header('Access-Control-Request-Method: *');
header('Access-Control-Allow-Methods: POST, GET, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: *,x-requested-with,Content-Type');
header('X-Frame-Options: DENY');

Categories