I have an API with Slim3 framework, I have set headers but when I'm sending request from other website from frontend APP to API I got [OPTIONS] 405 Method Not Allowed and request blocked because rule „Same Origin Policy” not allowed to load from ...
I have tried:
$app->options('/{routes:.+}', function ($request, $response, $args) {
return $response;
});
$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, PATCH, OPTIONS');
});
not working...
$app->add(new CorsMiddleware([
"origin" => ["*"],
"methods" => ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
"headers.allow" => [],
"headers.expose" => [],
"credentials" => false,
"cache" => 0,
]));
Also not working...
Now my middleware.php looking like:
use Slim\Http\Request;
use Slim\Http\Response;
use Tuupola\Middleware\CorsMiddleware;
$app->add(function (Request $request, Response $response, callable $next) {
$uri = $request->getUri();
$path = $uri->getPath();
if ($path != '/' && substr($path, -1) == '/') {
// permanently redirect paths with a trailing slash
// to their non-trailing counterpart
$uri = $uri->withPath(substr($path, 0, -1));
if($request->getMethod() == 'GET') {
return $response->withRedirect((string)$uri, 301);
}
else {
return $next($request->withUri($uri), $response);
}
}
return $next($request, $response);
});
$app->add(new CorsMiddleware([
"origin" => ["*"],
"methods" => ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
"headers.allow" => [],
"headers.expose" => [],
"credentials" => false,
"cache" => 0,
]));
$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')
->withheader('Allow', 'GET, POST, PUT, DELETE, OPTIONS' );
});
Frontend side just async fuction with fetch:
async (formData) => {
const response = await fetch(apiUrl,
{
method:'post',
mode:'cors',
body:formData,
headers: {
'Content-type': 'application/json'
},
redirect: 'follow'
});
return response.json();
}
Anyone have some ideas?