How to send an HTTP PUT request from Haxe / Neko?

I have a server under NekoVM that provides a RESTLike service. I am trying to send a PUT / DELETE request to this server using the following Haxe code:

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" ); } 

The problem is that only the onStatus event shows something:

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

Can someone explain to me what I'm doing wrong with customRequest ?

+5
source share
2 answers

customRequest does not call onData .

After the call to customRequest is onError , either customRequest is onError , or the first onStatus was called, then the response was written to the specified output.

+2
source

For those who find these answers (@stroncium correct) and are wondering what the finished code might look like:

 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()); } 

I made the point

0
source

Source: https://habr.com/ru/post/1208537/


All Articles