Search code examples
javascriptnode.jsapiexpressxmlhttprequest

How to get XMLHttpRequest responseText returned inside a express.router API function Nodejs


I'm trying to make my API function return the XML response. I know XMLHttpRequest is async. I can log the response, but I can't bring the response one level up in the scope. How can I acheive this so I can make my express router function return the response?

I can log the response like this:

router.post('/frete', async(req,res) =>{

    try{

        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {

            if (this.readyState === 4) {
                console.log(this.responseText)
            }
        };

        xhr.open("GET", someUrl);
        xhr.send();

        //return res.send('The elusive XML response')

    }catch(err){
        console.error(err);
        return res.status(500).send('Server error.')
    }

});

I have tried many many tweaks to bring this responseText one level up in the scope, so my API function returns something, but no success.

Thanks for the help.


Solution

  • try this. I've added application/xml in header which means it'll show xml in response and I've moved res.send inside if condition. because you're sending response at the end of try block but till that time your someurl is not resolved.

    router.post('/frete', async(req, res) =>{
    
        try{
    
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function() {
    
                if (this.readyState === 4) {
                    console.log(this.responseText)
                    res.type('application/xml');
                    res.send(this.responseText);
                }
            };
    
            xhr.open("GET", someUrl);
            xhr.send();
    
        } catch(err) {
            console.error(err);
            return res.status(500).send('Server error.')
        }
    
    });