如何从nodejs中获取ajax中的响应

时间:2018-01-27 19:38:13

标签: jquery node.js ajax

我正在尝试提交表单,然后通过AJAX发送状态success。 但是当我在提交表单后从NodeJS发送状态时,它没有到达AJAX代码,因为我已经发出alert()语句来检查它是否到达它。警报未被触发,但它会直接打印我在send('this text is printed')中写的那个值。

我的test.js文件是

$(document).ready(function() {
    $('#form_submit').click(function() {
        $.ajax({
            url: '/submitForm',
            type: 'POST',
            contentType: 'application/json',
            success: function(result) {
                alert(result.status);
                if (result.status === "success") {
                    alert("success");
                    window.location = '/nextPage';

                } else {
                    alert("failure");
                }

            },
            error: function(err) {
                alert('error');
            }
        })
    });
});

我的NodeJS代码在下面给出

app.post('/submitForm', function(req, res) {
    // submitted form to database
    var form = new Form({
        name: req.body.name,
        email: req.body.email,
        number: req.body.number,
    });
    form.save(function(err) {
        if (err) {
            throw new Error(err);
        } else {
            res.send({
                status: 'success',
                message: 'successfully form created'
            });
        }
    });
});

1 个答案:

答案 0 :(得分:-1)

您必须将res.send()更改为res.json()才能发送JSON数据。