Search code examples
javascriptajaxcontent-typeform-data

Why isn't my server receiving any content?


I have this :

function base64ToBlob(base64, mime) 
{
    mime = mime || '';
    var sliceSize = 1024;
    var byteChars = window.atob(base64);
    var byteArrays = [];

    for (var offset = 0, len = byteChars.length; offset < len; offset += sliceSize) {
        var slice = byteChars.slice(offset, offset + sliceSize);

        var byteNumbers = new Array(slice.length);
        for (var i = 0; i < slice.length; i++) {
            byteNumbers[i] = slice.charCodeAt(i);
        }

        var byteArray = new Uint8Array(byteNumbers);

        byteArrays.push(byteArray);
    }

    return new Blob(byteArrays, {type: mime});
}


function send() {
    let blob = base64ToBlob(picture, "image/jpeg");
    let formData = new FormData();
    formData.append("picture", blob)
    formData.append("a", 70)
    formData.append("b",  5)
    
    var request = new XMLHttpRequest();
    request.open("GET", "server/far/away/that/need/content-type");
    request.setRequestHeader("Content-type", "HELP HERE")
    request.send(formData);
}

When I call the send function, my server (cloud function for firebase) don't receive any data. I think that's because there is no content-type and the server can't use data that I send.

That's why I need the content type.

Sorry, my english isn't perfect :/ (I'm French)


Solution

  • When I call the send function, my server (cloud function for firebase) don't receive any data.

    That's because you're using the wrong HTTP method. GET has no body, but it's the body where you're sending the data:

    var request = new XMLHttpRequest();
    request.open("GET", "server/far/away/that/need/content-type");
    //           ^^^^----------------------------------------------- method
    request.setRequestHeader("Content-type", "HELP HERE")
    request.send(formData);
    //           ^^^^^^^^------------------------------------------- request body
    

    From MDN:

    send() accepts an optional parameter which lets you specify the request's body; this is primarily used for requests such as PUT. If the request method is GET or HEAD, the body parameter is ignored and the request body is set to null.

    The content type probably doesn't matter that much, but if you're sending the data in the body like that, you need to use POST or PUT.