由于我已经升级到Slim v3
我所有的GET
和POST
路线都运行良好,但PUT
路线却不行。我有一个班级,我做这样的事情:
$this->slimObj->put('/path/{ID}', array($this, 'method'));
function method ( $request, $response, $args ) {
$response = $response->withHeader('Content-type', 'application/json');
$response = $response->withHeader('Access-Control-Allow-Origin', '*');
$ID = $args['ID'];
// ...
return $response;
}
我使用 Chrome 48
调试我的 Cordova
应用程序,并在PUT
调用后收到此错误:
XMLHttpRequest cannot load
http://example.com/file.php/path/149. No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:4400' is therefore not allowed access. The response had HTTP status code 400.
我对GET
和POST
请求使用类似的回调,它们工作正常,我不明白为什么它对PUT
不起作用.
当从curl
调用它时,它可以工作:
curl -X PUT -H 'Content-Type: application/json' -d '{"data": 5 }' http://example.com/file.php/path/149
我使用 ajax
从 JS
调用 Slim API 函数:
$.ajax({
type: 'PUT',
url: 'http://example.com/file.php/path/149',
dataType: "json",
data: {
"data": 5
},
success: function(result) {
// ...
},
error: function() {
// Always getting error
}
});
如何让它从Chrome 48
工作?
我不太确定,但我认为以前的Chrome
版本一切正常。
谢谢
我刚刚通过添加以下内容解决了:
$this->slimObj->add(function ($request, $response, $next) {
$response = $response->withHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');
$response = $next ($request, $response);
return $response;
});
在初始化任何路由之前。