1

我很难将双向数据从 html 页面传输到我的 node.js 应用程序,然后再返回到 html 页面。

我很确定我已经找到了正确的解决方案,但我只是没有让它发挥作用。

我将以下内容用于我的 node.js 应用程序:

var express = require('/usr/lib/node_modules/express');
var app = express();

app.use(function(err, req, res, next){
  console.error(err.stack);
  res.send(500, 'Something broke!');
});

app.use(express.bodyParser());

app.post('/namegame', function(req, res)
    {
        console.log('Got request name: ' + req.body.name);
        setTimeout(function() 
        { 
            var newName = "New Name-O";
            res.send({name: newName});
        }, 2000);
    }
);

app.listen(8088, function() { console.log("Server is up and running");  });

以下是我的html页面:

<html> 
<head> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script> 

    <script type="text/javascript"> 
        // wait for the DOM to be loaded 
        $(document).ready(function() 
        {
            alert("Got here!");

            function DisplayName(response)
            {
                alert(response.newName);
            }

            $("#NameGameIt").click(function(event)
            {
                alert("How about now?");
                //event.PreventDefault();
                var nameSubmitted = document.getElementById("name");
                //var nameSubmitted = "help!!";

                alert("Name: " + nameSubmitted.value);

                $.ajax({
                    type:       "POST",
                    url:        "http://127.0.0.1:8088/namegame",
                    data:       {name: nameSubmitted.value},
                    dataType:   "json",
                    timeout:    2500,
                    success:    function() { alert("???");},
                    error:      function(error1, error2, error3)
                    {   alert("error"); },
                    complete:   function(arg1, arg2, arg3)
                    {   alert("complete");  }
                });

            });

        });

    </script>

</head> 
<body>

<h1>Test form for Ajax</h1>
</br>

Name: <input type="text" id="name" name="name"></br>
<input type="button" value="NameGameIt" id="NameGameIt">
</form>

</body>
</html>

因此,当我运行节点应用程序时,服务器运行良好。当我启动 html 页面时,我收到警报“到了这里!” 当我按下“NameGameIt”按钮时,我会收到“现在怎么样?”的警报。然后是警报“名称:”+我输入的任何名称。一旦我单击该警报,节点应用程序会立即看到该帖子并将名称打印到控制台。两秒钟后,当节点发送响应时,浏览器将直接进入 ajax 帖子上的错误处理程序。错误处理程序中唯一有用的数据是它是一个没有真正用处的“错误”。

所以我知道消息是从 html 页面到达节点的,因为它会打印出我发送的名称,并且我知道 html 页面正在从节点获取消息,因为在节点超时之前它不会出错发生触发发送。但是,我不知道为什么它继续将我发送到错误处理程序而不是成功。我已经使用 node-inspector 逐步完成了节点代码,它似乎使用 200 成功代码正确构建了数据包,它在完成数据包制作后在 .send 内部调用 .end 所以我不认为其中任何一个都在咬我。

我快要疯了!如果有人看到我遗漏的内容或对收集更多信息的方法有任何新想法,我将非常感谢您的帮助。

4

2 回答 2

2

您的代码非常好,但您几乎肯定会遇到跨域 AJAX 请求问题。您可能正在本地文件系统上打开此 HTML 文件并以这种方式发出请求,这就是导致此问题的原因。

要修复它,请app.use(express.static('public'));像这样添加:

var express = require('/usr/lib/node_modules/express');
var app = express();

app.use(function(err, req, res, next){
  console.error(err.stack);
  res.send(500, 'Something broke!');
});

app.use(express.bodyParser());
app.use(express.static('public'));

app.post('/namegame', function(req, res)
    {
        console.log('Got request name: ' + req.body.name);
        setTimeout(function() 
        { 
            var newName = "New Name-O";
            res.send({name: newName});
        }, 2000);
    }
);

app.listen(8088, function() { console.log("Server is up and running");  });

然后将您的 html 文件放在“公共”文件夹中。启动服务器后,您可以访问http://127.0.0.1:8088/file.html并且您的代码将运行良好。

于 2013-04-18T01:05:58.377 回答
1

就我而言,将其添加到app.js作品中。

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

https://enable-cors.org/server_expressjs.html

于 2017-09-02T15:55:20.490 回答