Monday, 1 May 2017

Opening an http/2 connection and POSTing form-data

Objective

The objective of this code is to connect to an API service over http2, then maintain that connection so I may be able to POST multipart form data to the API:

let options = {
    port: 443,
    hostname: 'avs-alexa-na.amazon.com',
    path: '/v20160207/directives',
    method: 'GET',
    headers: {
      'Authorization': 'Bearer ' + JSON.parse(localStorage.getItem('CREDS')).access_token,
    }
  }
  var request = require('http2').request(options)
  request.on('response', function(response) {
    console.log(response)
    if (response.statusCode == 403) {
       //handle invalid token
    } else {
      //now lets make a POST request with form-data
    }
    //response.on('end', finish);
  });

The Issue

I looked over the HTTP module docs and I saw use cases in which when you associate the request with a variable, you could use request.write() to send data, but I'm not entirely sure thats the right way to go about sending form-data. then I looked over the form-data module with this example:

var request = http.request({
  method: 'post',
  host: 'example.org',
  path: '/upload',
  headers: form.getHeaders()
});

form.pipe(request);

request.on('response', function(res) {
  console.log(res.statusCode);
});

But in this case, I want to send form-data AFTER Ive established a connection with the API service and while on the same connection, as the API Docs says

" After establishing the downchannel stream, your client must synchronize it’s components’ states with AVS. This requires making a POST request to //events on a new event stream on the existing connection (Note: Do not open a new connection). This event stream should be closed when your client receives a response (directive). The following is an example SynchronizeState event: "

So If I were to create another variable for another http2 request to another path using POST method, wouldn't that be creating a new connection?

I've successfully made a GET request to the API endpoint of that service, now it's a matter of POSTing form-data (multipart, if that makes a difference) to a different path while on the same existing connection.

Any help would be appreciated!



via Vikaton

No comments:

Post a Comment