来自express js的Ajax post响应不断抛出错误

Ajax post response from express js keeps throwing error

本文关键字:出错 错误 响应 post express js Ajax 来自      更新时间:2023-09-26

我有一个真正的困难的时间站起来双向数据传输从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"按钮时,我得到的提示是"How about now?",然后是提示"Name:"+我输入的任何名称。单击该警报后,节点应用程序立即看到该帖子并将其名称打印到控制台。两秒钟后,当节点发送响应时,浏览器将直接进入ajax帖子上的错误处理程序。在错误处理程序中出现的唯一有用的数据是它是一个"错误",而不是真正有用的。

所以我知道消息是从html页面到达节点的,因为它打印出了我发送的名称,并且我知道html页面正在从节点获取消息,因为它不会出错,直到节点上的超时发生触发发送。但是,我不知道为什么它一直把我发送到错误处理程序,而不是成功。我已经使用node-inspector在节点代码中完成了所有的步骤,它似乎正确地使用200代码成功构建数据包,并且在完成制作数据包后,它在。send中调用。end,所以我不认为这两件事都在咬我。

我要疯了!如果有人看到我遗漏了什么,或者有任何关于收集更多信息的新想法,我将非常感谢你的帮助。

您的代码非常好,但是您几乎肯定会遇到跨域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

相关文章: