Friday, 26 May 2017

Node.js Axios for local Server Side script call

I have a Node.js application running on port 3000 that is using axios for it's server side ajax calls.

It is working as follows

My axio ajax call is made in /public/views/example.js

example() {

    axios.get (
        // server ip, port and route
        "http://192.168.1.5:3000/example", {
            params : {
                arg01: "nothing"
            }
        }
    )
    .then (
        result => console.log(result)
    )
    .catch (
        error => console.log(error)
    );

}

and the route it is calling /public/logic/example_route.js

router.get("/example", function(req, res) {

    // just to test the ajax request and response

    var result = req.query.arg01;
    res.send(result);

});

So this is all working fine when I run it from inside the network but if I try to run it from outside of the network (using the DNS that has the 3000 port forwarded) it fails and I imagine it is because when executing externally 192.168.1.5 is no longer valid as I have to use the DNS.

When I change the axios call to the following

example() {

    axios.get (
        // server ip, port and route
        "http://www.dnsname.com:3000/example", {
            params : {
                arg01: "nothing"
            }
        }
    )
    .then (
        result => console.log(result)
    )
    .catch (
        error => console.log(error)
    );

}

Then it works again externally but not internally. Is there a way around this issue?

I know that when making ajax calls with php I don't have this problem because I can use the actual location of the script instead of a route

$.ajax({
    url      : "logic/example.php",
    type     : "GET",
    dataType : "json",
    data     : {
                  "arg01":"nothing"
               },
    success  : function(result) {
                  console.log(result);
               },
    error    : function(log) {
                  console.log(log.message);
               }
});

Is it possible to achieve something similar with Node.js and axios?



via Trent

No comments:

Post a Comment