Slim Framework v3 - PUT 路由的问题

Slim Framework v3 - Problems with PUT routes

本文关键字:路由 问题 PUT Framework v3 Slim      更新时间:2023-09-26

由于我已经升级到Slim v3我所有的GETPOST路线都运行良好,但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.

我对GETPOST请求使用类似的回调,它们工作正常,我不明白为什么它对PUT不起作用.

当从curl调用它时,它可以工作:

curl -X PUT -H 'Content-Type: application/json' -d '{"data": 5 }' http://example.com/file.php/path/149

我使用 ajaxJS 调用 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;
});

在初始化任何路由之前。