How to post an plaintext data to server using XMLHttpRequest, React and Express as demo
井民全, Jing, mqjing@gmail.com

Github: (view)
1. Quick
1.1. Client
const urlBinaryResourceApi:string = 'data/binary-resource'; let xhr = new XMLHttpRequest(); xhr.open('Post', urlBinaryResourceApi); var blob = new Blob(['abc123'], {type: 'text/plain'}); xhr.send(blob);
|
1.2. Server
var bodyParser = require('body-parser'); app.use(bodyParser.text()); // for request content-type: text/plain
app.post(...){ // Access plain text data 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')); ) |
2. Detail
2.1. Client
async function TestPostBlob(){ const urlBinaryResourceApi:string = 'data/binary-resource'; let xhr = new XMLHttpRequest(); xhr.open('Post', urlBinaryResourceApi); var blob = new Blob(['abc123'], {type: 'text/plain'}); xhr.send(blob);
xhrEventHandle(xhr); }
|
Sent Html header
// -- Server received headers -- // 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":"text/plain","content-length":"6","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: text/plain app.use(bodyParser.text());
// 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: Response to client let strMsg:string = '[server] api: binary-resource, ok.'; console.log(strMsg); res.send(strMsg) });
module.exports = router;
|
3. References
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
Get HTTP POST Body in Express.js, https://stackabuse.com/get-http-post-body-in-express-js
How to get the JSONized body and raw body while using body-parser in the nodejs express project, https://www.programmersought.com/article/14781326503/