【问题标题】:Node.js Axios for local Server Side script callNode.js Axios 用于本地服务器端脚本调用
【发布时间】:2017-05-26 13:40:01
【问题描述】:

我有一个 Node.js 应用程序在端口 3000 上运行,它使用 axios 进行服务器端 ajax 调用。

它的工作原理如下

我的 axio ajax 调用是在 /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)
    );

}

以及它调用的路由/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);

});

所以当我从网络内部运行它时一切正常,但是如果我尝试从网络外部运行它(使用转发 3000 端口的 DNS)它会失败,我想这是因为执行时外部 192.168.1.5 不再有效,因为我必须使用 DNS。

当我将 axios 调用更改为以下内容时

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)
    );

}

然后它再次在外部而不是内部工作。有没有办法解决这个问题?

我知道在使用 php 进行 ajax 调用时我没有这个问题,因为我可以使用脚本的实际位置而不是路由

$.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);
               }
});

有没有可能用 Node.js 和 axios 实现类似的东西?

【问题讨论】:

  • 您是否尝试过仅使用 /example 作为 url 而不是 http://www.dnsname.com:3000/example
  • 哇,好用,我不知道它这么聪明,你能不能把这个答案贴出来,这样我就可以接受它是正确的
  • 酷。添加了答案。谢谢

标签: javascript node.js ajax axios


【解决方案1】:

您可以使用没有实际主机和端口的路径。

example() {    
    axios.get (
        // just the path without host or port
        "/example", {
            params : {
                arg01: "nothing"
            }
        }
    )
    .then (
        result => console.log(result)
    )
    .catch (
        error => console.log(error)
    );    
}

【讨论】:

  • 非常感谢,我没想到解决方案会这么好:D
猜你喜欢
  • 1970-01-01
  • 2014-06-20
  • 2016-12-17
  • 1970-01-01
  • 2019-02-01
  • 1970-01-01
  • 2012-01-12
  • 2018-06-08
  • 1970-01-01
相关资源
最近更新 更多