0

我尝试使用 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;
});

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

我究竟做错了什么?

4

1 回答 1

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;
}
于 2020-10-08T13:24:33.893 回答