【问题标题】:Send a message from client to server从客户端向服务器发送消息
【发布时间】:2014-11-20 17:17:13
【问题描述】:

我有一个我用 NodeJs 编写的服务器,它监听端口 1234。 我想从我的客户端 (html) 向我的服务器发送请求并等待答复。

我尝试使用 XMLHttpRequest:

        var http = new XMLHttpRequest();
        var url = "127.0.0.1:1234";
        var params = "token=22";
        http.open("post", url, true);//"https://www.google.com/search?q=asd"
        http.setRequestHeader("Content-type", "text/html");
        http.setRequestHeader("Content-length", 0);
        http.setRequestHeader("Connection", "keep-alive");
        http.onreadystatechange = function() {//Call a function when the state changes.
            alert(http.responseText);
        }

        http.ontimeout = function()
        {
            alert("timeout");
        }

        http.timeout=10;
        try
        {
            http.send(null);
        }
        catch(ex)
        {
            alert(ex);
        }

但我总是遇到异常。原因是我不能使用自己的端口。

还有其他方法可以发送请求并得到响应吗?

【问题讨论】:

    标签: html node.js client-server


    【解决方案1】:

    使用JQuery.ajax 让您的生活更轻松并没有错,使用 jquery 确实会变得更轻松,尤其是在涉及 XMLHttpRequest 时。

    【讨论】:

    • 我需要使用 JSONP 才能使用不同的端口
    • 如果你真的阅读jquery文档你会发现它支持jsonp请求
    猜你喜欢
    • 2017-01-12
    • 1970-01-01
    • 2015-01-05
    • 2017-07-30
    • 1970-01-01
    • 1970-01-01
    • 2014-03-16
    相关资源
    最近更新 更多