Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using StringTools;
- import js.node.Https;
- import js.node.http.IncomingMessage;
- import js.node.Buffer;
- import js.Promise;
- import js.Error;
- import haxe.extern.EitherType;
- class ExampleHttpPost
- {
- public static function example()
- {
- fetch_cookie().then(fetch_result).then(function(result:String)
- {
- trace('POST data : $result');
- }).catchError(function(error_message:String)
- {
- trace('Error occured : $error_message');
- });
- }
- public static function fetch_cookie():Promise<String>
- {
- return new Promise(function(resolve, reject)
- {
- var data:String = '';
- var cookies:Array<String>;
- var cookie:String;
- var request = Https.get(
- {
- protocol: 'https:',
- method: 'GET',
- host: 'example.com',
- path: '/api'
- },
- function(input:IncomingMessage)
- {
- cookies = input.headers['set-cookie'];
- if(cookies == null)
- {
- reject('HTTP header \'Set-cookie\' was not recovered ¯\\_(ツ)_/¯');
- }
- else
- {
- cookie = cookies.join(';');
- resolve(cookie);
- }
- });
- request.on('error', function(error:Error)
- {
- reject(error.message);
- });
- });
- }
- public static function fetch_result(cookie:String):Promise<String>
- {
- return new Promise(function(resolve, reject)
- {
- var data:String = '';
- var request = Https.request(
- {
- protocol: 'https:',
- method: 'POST',
- host: 'example.com',
- path: '/api',
- headers:
- {
- 'Content-Type' : 'application/x-www-form-urlencoded',
- 'Cookie' : cookie
- }
- },function(input:IncomingMessage)
- {
- if(input.statusCode != 200) reject('status != 200, status = ${input.statusCode}');
- input.on('data', function(chunk:EitherType<Buffer, String>)
- {
- data += chunk;
- });
- input.on('end', function()
- {
- resolve(data);
- });
- });
- request.on('error', function(error:Error)
- {
- reject(error);
- });
- request.write('param=a', function()
- {
- request.end();
- });
- });
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement