【问题标题】:getting response from post request从发布请求中获得响应
【发布时间】:2017-07-29 10:19:55
【问题描述】:

我正在尝试使用 POST jQuery AJAX 进行简单的登录模式, 但我没有收到来自服务器的任何响应

客户:

$(document).ready(function(){
            $("#loginReq").click(function(){
                $.post("/login",
                {
                    uname: document.getElementById("username").value,
                    psw: document.getElementById("password").value
                },
                function(data, status, jqXHR) {
                    alert("Data: " + data + "\nStatus: " + status);
                });
            });
        });

服务器:

app.post('/login', function (req, res) {
var username = req.body.uname;
var password = req.body.psw;
var i;
for (i=0; i < users.length; i++)
    if (username == users[i].username && password == users[i].password)
    {
        console.log('found');
        //res.send('OK');
        //res.sendStatus(200);
        res.status(200).send('OK');
        break;
    }
if (i == users.length)
{
    console.log('not found');
    res.sendStatus(300);
}
console.log('end of listener');
});

我试过 res.sent、res.end、res.statusCode、res.status.send, 但无论我在客户端尝试什么警报都不会弹出。

(我的目标是得到一个空响应——只有状态码,没有正文, 但没有任何效果)

【问题讨论】:

  • 控制台错误服务器和客户端?

标签: javascript ajax node.js express


【解决方案1】:

这是一个简单的例子,我认为应该对你有所帮助。

第一个npm install body-parser

在您的服务器上使用 body-parser 中间件:

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.post('/login', (req, res)=> {
    res.send(JSON.stringify(req.body));
});

在您的 jQuery 文件中阻止表单提交 - 请注意,loginReq 是表单本身的 id:

$(document).ready(function(){
    $('#loginReq').submit(function(e) {
        e.preventDefault();
        $.ajax({ 
           url: '/login',
           type: 'POST',
           cache: false, 
           data: {"username": document.getElementById("username").value}, 
           success: function(data){
              alert(data);
           }
           , error: function(jqXHR, textStatus, err){
               alert('error ' + err);
           }
        });    
    });
});

这将弹出一个包含您的数据的警报。

【讨论】:

    【解决方案2】:

    您已在后端定义了一个服务器,但尚未启动它。查看 express 网站here 上的示例代码,了解如何启动您的服务器。

    TL;DR - 尝试将以下内容添加到服务器文件的底部:

    app.listen(3000, function () {
      console.log('Example app listening on port 3000!')
    })
    

    【讨论】:

      猜你喜欢
      • 2020-04-20
      • 2020-02-08
      • 1970-01-01
      • 1970-01-01
      • 2016-06-09
      • 1970-01-01
      • 1970-01-01
      • 2017-06-22
      • 1970-01-01
      相关资源
      最近更新 更多