Javascript 从post请求获取响应

Javascript 从post请求获取响应,javascript,ajax,node.js,express,Javascript,Ajax,Node.js,Express,我正在尝试使用POST jQuery AJAX实现简单的登录模式, 但我没有收到服务器的任何响应 客户: $(document).ready(function(){ $("#loginReq").click(function(){ $.post("/login", { uname: document.getElementById("username").value,

我正在尝试使用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');
});
app.post('/login',函数(req,res){
var username=req.body.uname;
var密码=req.body.psw;
var i;
对于(i=0;i
我试过res.send,res.end,res.statusCode,res.status.send, 但是无论我在客户端尝试了什么,警报都不会弹出

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

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

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

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

这里有一个简单的例子,我想应该对你有所帮助

首先
npm安装主体解析器

在服务器上,使用主体解析器中间件:

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

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

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