为什么尽管设置了标头,CORS仍然无法工作?

问题描述

我有一个使用Slim3框架的API,我设置了标头,但是当我从前端APP向其他网站向API发送请求时,我收到了[OPTIONS] 405方法不允许,请求被阻止,因为规则“ Same Origin Policy”不存在允许从...加载...

我尝试过:

$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');
});

不起作用...

$app->add(new CorsMiddleware([
    "origin" => ["*"],"methods" => ["GET","POST","PUT","PATCH","DELETE","OPTIONS"],"headers.allow" => [],"headers.expose" => [],"credentials" => false,"cache" => 0,]));

也无法正常工作...

现在我的middleware.PHP看起来像:

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,-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" => ["*"],]));

$app->add(function ($req,$res);

    return $response
        ->withHeader('Access-Control-Allow-Origin','*')
        ->withHeader('Access-Control-Allow-Headers',Authorization')
        ->withHeader('Access-Control-Allow-Methods',OPTIONS')
        ->withheader('Allow',OPTIONS' );
});

前端仅与提取异步功能

async (formData) => {
        const response = await fetch(apiUrl,{
            method:'post',mode:'cors',body:formData,headers: {
                'Content-type': 'application/json'
            },redirect: 'follow'
        });

        return response.json();
    }

有人有想法吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...