0

I need help: I'm running express in node JS and I'm trying to pass an image through an HTTP request and or response

Express initialization:

var app = express();
app.engine('.html', require('ejs').__express);
app.set('views', __dirname + '/views');
app.set('view engine', 'html');
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.text({type:'text/plain'}));

Http request (ajax inside index.html):

var request = new XMLHttpRequest();
request.open('GET', '/request');
request.setRequestHeader('Content-Type', 'text/plain');
request.onreadystatechange = function() {
    if(request.readyState == 4){
        //do stuff with request.responseText
    }
};
request.send('request for image xxxx');

Express handling the request:

app.get('/request', (req, res) => {
    if(req.body == 'request for image xxxx')
        res.status(200).send(???);
    //other stuff
});

My middle-ware 'bodyParser' does support other data types if they are url-encoded, but I have no idea how to do that, so I'm forced to only use text/plain messages, except there comes a problem when I want to send an image over.

I'm guessing I could probably do that using buffers maybe, but I have absolutely no idea what the syntax for that would be and the HTTP handling syntax I'm already using is probably extremely over-complicated or something. I'm quite new to HTTP protocols.

  • your post is too complicated. what do you want to do? if i`m not wrong you want to post a image to your server. am i right? – defectivepixel Aug 28 '18 at 11:32
  • i want to send an image over an HTTP request/response, I'm using the middle-ware `bodyParser.text({type:'text/plain'})` because I haven't found a better way yet. So I either need a better middle-ware to send images over, or someway to convert an image to text and back again. – Jordan Paschal Aug 28 '18 at 23:15

1 Answers1

0

You can encode the image into base64 and send it as text. Upon receiving on server write that as an image.

var base64Data = 'base64encoded'
require("fs").writeFile("image.png", base64Data, 'base64', function(err) {
    console.log(err);
});
Wesgur
  • 3,140
  • 3
  • 18
  • 28