6

我有一个在 NekoVM 下运行的服务器,它提供 RESTLike 服务。我正在尝试使用以下 Haxe 代码向该服务器发送 PUT/DELETE 请求:

static public function main()
{
    var req : Http = new Http("http://localhost:2000/add/2/3");
    var bytesOutput = new haxe.io.BytesOutput();

    req.onData = function (data)
    {
        trace(data);
        trace("onData");
    }

    req.onError = function (err)
    {
        trace(err);
        trace("onError");
    }

    req.onStatus = function(status)
    {
        trace(status);
        trace("onStatus");
        trace (bytesOutput);
    }

    //req.request(true); // For GET and POST method

    req.customRequest( true, bytesOutput , "PUT" );

}

问题是只有onStatus事件显示一些东西:

Main.hx:32: 200
Main.hx:33: onStatus
Main.hx:34: { b => { b => #abstract } }

谁能解释我做错了customRequest什么?

4

2 回答 2

3

customRequest不叫onData

customRequest调用完成后,要么被onError调用,要么首先onStatus被调用,然后将响应写入指定的输出。

于 2014-12-20T12:58:43.443 回答
1

对于那些找到这些答案(@stroncium's是正确答案)并想知道完成的代码可能是什么样子的人:

static public function request(url:String, data:Any) {
    var req:Http = new haxe.Http(url);
    var responseBytes = new haxe.io.BytesOutput();

    // Serialize your data with your prefered method
    req.setPostData(haxe.Json.stringify(data)); 
    req.addHeader("Content-type", "application/json");

    req.onError = function(error:String) {
        throw error;
    };

    // Http#onData() is not called with custom requests like PUT

    req.onStatus = function(status:Int) {
        // For development, you may not need to set Http#onStatus unless you are watching for specific status codes
        trace(status);
    };

    // Http#request is only for POST and GET
    // req.request(true);

    req.customRequest( true, responseBytes, "PUT" );

    // 'responseBytes.getBytes()' must be outside the onStatus function and can only be called once
    var response = responseBytes.getBytes();

    // Deserialize in kind
    return haxe.Json.parse(response.toString());
}

我做了一个要点

于 2019-02-02T15:25:02.497 回答