2021年6月26日 星期六

[html, xhr, post] How to post an ArrayBuffer data to server using XMLHttpRequest, React and Express as demo

How to post an ArrayBuffer data to server using XMLHttpRequest, React and Express as demo

井民全, Jing, mqjing@gmail.com


 Github: (view)

1. Quick

1.1. Client

  var xhr = new XMLHttpRequest;

  xhr.open("POST", urlBinaryResourceApi) 

  xhr.setRequestHeader('Content-Type', 'application/octet-stream');   ////< ------- 

  xhr.send(myArray);


1.2. Server

var bodyParser  = require('body-parser');

// app.use(bodyParser.raw()); // ok

app.use(bodyParser.raw({type: 'application/octet-stream'})); 


app.post(...){


    // Access the arrayBuffer data

    if(req.get('content-type') == 'application/octet-stream'){

        console.log('Get application/octet-stream type');

        let myArrayBuffer = req.body as ArrayBuffer;

        var longInt8View = new Uint8Array(myArrayBuffer);

        for (var i=0; i< longInt8View.length; i++) {

            console.log('longInt8View = ', longInt8View[i]);

        }

    }


)


2. Detail

2.1. Client

async function TestPostArrayBuffer(){

  console.log('TestPostArrayBuffer');

  const urlBinaryResourceApi:string = 'data/binary-resource';

  var myArray = new ArrayBuffer(512);

  var longInt8View = new Uint8Array(myArray);


  // generate some data

  for (var i=0; i< longInt8View.length; i++) {

    longInt8View[i] = i % 256;

  }


  var xhr = new XMLHttpRequest;

  xhr.open("POST", urlBinaryResourceApi) 

  xhr.setRequestHeader('Content-Type', 'application/octet-stream');   ////< ------- 

  xhr.send(myArray);


  console.log('[client] sent: myArray = ' + myArray);

  xhrEventHandle(xhr);

}



Sent Html header

header = {"host":"localhost:9000","user-agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:89.0) Gecko/20100101 Firefox/89.0","accept":"*/*","accept-language":"en-US,en;q=0.5","accept-encoding":"gzip, deflate",    "content-type":"application/octet-stream","content-length":"512","origin":"http://localhost:9000","connection":"keep-alive","referer":"http://localhost:9000/","dnt":"1","sec-gpc":"1"}



2.2. Server

import express, {Request, Response} from 'express';


var router = express.Router();

var bodyParser  = require('body-parser');


// Step 1: for request content-type: application/octet-stream

router.use(bodyParser.raw({type: "application/octet-stream"})); 

//router.use(bodyParser.raw()); // ok


// api: data/binary-resource

router.post('/binary-resource', function(req:Request, res:Response, next) {

    console.log('[server] received api: binary-resource, header = ' + JSON.stringify(req.headers))

    console.log('[server] body = ' + req.body);

    console.log('[server] Content-Type = ' + req.get('content-type'));


    // Step 2: Access the arrayBuffer data

    if(req.get('content-type') == 'application/octet-stream'){

        console.log('Get application/octet-stream type');

        let myArrayBuffer = req.body as ArrayBuffer;

        var longInt8View = new Uint8Array(myArrayBuffer);

        for (var i=0; i< longInt8View.length; i++) {

            console.log('longInt8View = ', longInt8View[i]);

        }

    }



     // Step 3: Response to client

    let strMsg:string = '[server] api: binary-resource, ok.';

    console.log(strMsg);

    res.send(strMsg)

});


module.exports = router;



3. References

  1. Sending and Receiving Binary Data -- Receiving binary data using JavaScript typed arrays, https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data

  2. Get HTTP POST Body in Express.js, https://stackabuse.com/get-http-post-body-in-express-js

  3. How to get the JSONized body and raw body while using body-parser in the nodejs express project, https://www.programmersought.com/article/14781326503/