缺少SLIM PUT-Request CORS标头

问题描述

我尝试使用SLIM Framework v4后端设置Angular应用; Angular在本地运行,而Slim在Deploy Server上。因此需要CORS设置程序,我确实喜欢文档中给出的内容

$app->options('/{routes:.+}',function ($request,$response,$args) {
    return $response;
});

$app->add(function ($request,$handler) {
    $response = $handler->handle($request);
    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');
});

获取请求时,存在Acces-Control-Allow-Origin标头;没问题,一切正常。在提出请求时(示例):

$app->put('/event/{id}',function (Request $request,Response $response,$args) use ($app) {
$id = $args['id'];
$response
        ->withHeader('Access-Control-Allow-Origin',Authorization');
$response->getBody()->write('Test with $id');
return $response;
});

即使在函数添加了附加功能,标头也不出现在浏览器中的响应上。

我在做什么错了?

解决方法

请求和响应对象是不可变的。您可以尝试以下方法:

$app->put('/event/{id}',function (Request $request,Response $response,$args) {
    $id = $args['id'];

    $response = $response
        ->withHeader('Access-Control-Allow-Origin','*')
        ->withHeader('Access-Control-Allow-Headers','X-Requested-With,Content-Type,Accept,Origin,Authorization');

    $response->getBody()->write('Test with $id');

    return $response;
}

相关问答

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