无法将jquery AJAX用于工作节点js express

Cant get jquery AJAX to work node js express

本文关键字:工作 节点 js express 用于 AJAX jquery      更新时间:2023-09-26

我一直在尝试让ajax在node.js上工作。这是我第一次使用ajax,所以我一直在尝试使用控制台测试它,以检查它是否工作,但每次尝试都没有在控制台上得到响应。

这是我的密码。

<script>
function getMessage() {
    var data = $("#messageselect").val()
    $.ajax({
        url: "/message",
        type: "POST",
        data: JSON.stringify(data)
        dataType: 'json',
        success: function(data) {
            console.log(data);
        }
        error : function(err)
        console.log("error fetching message");
    });
}
</script>

服务器

app.post('/message', function(req, res) {
    console.log(JSON.stringify(req.body));

    Message.findOne({ 'page.message' : req.data }, function(err, message) {
        if(err)
            throw err;
        res.send(message);
    });
});

html

<form method="POST">
                        <select multiple="multiple" class="messageselect" onchange="getMessage()" id="messageselect">
                            <% if(message) { %>
                            <% for(i=messagecount-1;i>=0;i--) { %>
                            <option value="<%= message[i].page.message %>">From: <%= message[i].page.username %> Message: <%= message[i].page.messagetitle %></option>
                            <% } %>
                            <% } %>
                        </select><br><br><br>
                    </form>

我想这是代码中的一个打字错误:

var = data $("#messageselect").val()
//--^^--------------------------------worng way to assign.

jQuery.ajax()需要发送一个对象:

var data = { data : $("#messageselect").val() };

在服务器上,您可以使用req.body来获取发布的数据:

 console.log(req.body.data);

注意:

为此,您需要有body-parser,因此请确保将其包含在上面的代码配置中。

你能试试下面的$http格式吗,

$http.post(//url , //data )
   .success (function() {})
   .error(function() {});
$.ajax({
    url: "/message",
    type: "POST",
    data: JSON.stringify(data)
    dataType: 'json',
    success: function(data) {
        console.log(data);
    }
    error : function(err)
    console.log("error fetching message");
});

错误处理程序中缺少大括号

error : function(err) {
        console.log("error fetching message");
}

也许不是正确的方式,所以你也可以尝试:

$.ajax({
    url: '/message',
    type: 'POST',
    dataType: 'JSON',
    data: {JSON.stringify(data)},
    success: function(data) {
        console.log(data);
    }
    error : function(err) {
        console.log("error fetching message");
    }
});

您是否曾经尝试过使用curl在服务器上发布内容?

除了现有的答案外,您还应该通过AJAX请求传递正确的Content-Type

$.ajax({
    url: "/message",
    type: "POST",
    data: JSON.stringify(data)
    dataType: 'json',
    contentType: 'application/json' //here it is
    //...
});