来自快递js的Ajax发布响应不断抛出错误

我很难站起来从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页面:

     // 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"); } }); }); });    

Test form for Ajax


Name:

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

所以我知道消息是从html页面进入节点,因为它打印出我发送的名称,我知道html页面从节点返回消息,因为它不会在节点超时之前出错发生触发发送。 但是,我不知道为什么它继续向我发送error handling程序而不是成功。 我已经使用node-inspector在节点代码中一路走来,似乎正在使用200代码正确构建数据包以获得成功,并且在完成数据包之后调用.end .send所以我不会认为这些事情中的任何一个都在咬我。

我快要疯了! 如果有人看到我缺少的东西,或者对如何收集更多信息有任何新的想法,我将非常感谢你的帮助。

您的代码非常好,但您几乎肯定会遇到跨域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文件放在’public’文件夹中。 启动服务器后,您可以访问http://127.0.0.1:8088/file.html ,您的代码运行正常。

在我的情况下,将此添加到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