【问题标题】:SLIM PUT-Request CORS Header missing缺少 SLIM PUT-Request CORS 标头
【发布时间】:2021-01-23 12:57:21
【问题描述】:

我尝试使用 SLIM Framework v4 后端设置 Angular 应用程序; Angular 在本地运行,而 Slim 在部署服务器上。所以需要 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 标头;没问题,一切都按预期工作。根据 Put 请求(示例):

$app->put('/event/{id}', function (Request $request, Response $response, $args) use ($app) {
$id = $args['id'];
$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;
});

即使在函数中添加了额外的内容,浏览器的响应中也不存在标头。

我做错了什么?

【问题讨论】:

    标签: php angular slim slim-4


    【解决方案1】:

    请求和响应对象是不可变的。你可以试试这个:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-28
      • 1970-01-01
      • 1970-01-01
      • 2020-01-05
      • 2018-06-15
      • 2021-07-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多