问题描述
我尝试使用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;
}