javascriptmithril.js

m.request with deserialization property is not returning a string


As per the example in API documentation, I am trying to use the m.request utility (with the deserialization flag set) to grab the contents of a .txt file as a string;

var file = m.request({
    method: 'GET',
    url: 'file.txt', //
    deserialize: function(value) {
        return value;
    }
})

However, the output of

console.log(file);

is actually the string:

// function (){return arguments.length&&(a=arguments[0]),a}

not the expected content in the file. I am certain that I am missing something, or setting the m.request options incorrectly - can anyone point me in the right direction?


Solution

  • From your example it doesn't look like you're utilizing the deserializer right, but that's not your issue. But just FYI (per the docs) the deserializer:

    "By default, m.request uses JSON to send and receive data to web services. You can override this by providing serialize and deserialize options..."

    Your issue however is that the request function is asynchronous and thus returns a promise rather than the explicit values. You will need to receive the promise and execute on the value:

    var file = m.request({
        method: 'GET',
        url: 'file.txt', //
            deserialize: function(value) {
        return value;
        }
    });
    
    file.then(function(val) { console.log(val); }); 
    

    The deserialize will still be called, and you can access the value. This should solve your problem.