将请求发布到页面,而不是执行成功函数



我在我的JavaScript文件中具有以下代码:

$.ajax({type: 'POST',
        url: '/',
        data: {test: 'This is some random data.'},
        dataType: 'json',
        success: function(){
            console.log('success');
        },
        error: function(){
            console.log('err');
        }
});

在节点中我有以下内容:

app.post('/', function (req, res){
    console.log(req.body.test);
});

我的命令控制台正在正确记录JSON对象,但是我的网页没有执行"成功函数"。我不明白为什么在我的AJAX请求中调用错误函数的数据是正确的吗?

在节点js side中,您必须对请求做出回复,否则客户端不知道它的发展,因此无法触发成功或错误回调:

app.post('/', function (req, res){
    console.log(req.body.test);
    res.end();
    // or to send json back
    // res.json({hello: 'world'});
    // to go in error callback just send a request with a status code > 400
    // res.status(400).end('bad request');
});

您只能发送一个响应。

最新更新