mardi 14 juin 2016

How to get jQuery AJAX result from NodeJS endpoint?

I successfully made an ajax call to a endpoint that I set up. I send it a raw certificate as JSON, and the backend decodes it. Now, I can bring up the decoded result with a console.log but I can't figure out how to return it as the result.

Ajax Call:

    $("#decoderSubmit").on('click', function() {
        var body = $('#csr').val();
        if (!(body.match(new RegExp("-----BEGIN", 'i')))) {
            $('#csrFail').show();
        } else {
            if (body.match(new RegExp("REQUEST", 'i'))) {
                $("#csrAlert").show();
            } else
                $("#certAlert").show();

            decode(body);

        }
    });

    function decode(body) {

        $.ajax({
            type: 'POST',
            url: '/api/decoder',
            data: {
                body: body //cert/csr
            },
            dataType: 'JSON',
            timeout: 4500,
            success: callback,
            error: fail


        });

        function callback(data) {

            //decodedText = data;
            alert(data);
            //$("#decodeBody").append('<div>' + data + '</div>');

        }

        function fail(request, status, err) {
            console.log(err);
        }


    }

NodeJS Endpoint:

router.route('/decoder')
    //console.log('test');

.post(function(req, res) {
    let body = req.body.body; 
    decode(body, function(result) {
        res.json(result);
    });

    function decode(cert) {
        let file = randCertFileName(); // Get a random filename for out cert
        var result;
        fs.writeFile(file, cert, function(err) { // Write the cert to a file

            if (err) {
                console.error("Error writing certificate: " + error);
                throw err;
            } else {
                execute('certutil -dump ' + file, function(out) { // Execute the certutil dump command
                    //console.log(out);
                    result = out;
                    fs.unlink(file); // Delete the certificate file

                    //return result;

                });
            }
        });

    }
});

As I said, if I do a console.log(out) I can get the dump, but not otherwise. I've trawled thru many SO posts and from what I can see, I think I'm doing the AJAX call correctly, so the problem is probably in my endpoint.

Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire