【问题标题】:Body of post request is empty帖子请求正文为空
【发布时间】:2020-06-06 14:09:09
【问题描述】:

由于某种原因,我对 mongodb 数据库的 jquery 发布请求的正文始终为空。我已经在终端上的 insomnia 和 python 等其他应用程序上尝试了相同的发布请求。

但是,这个与快递服务器同目录的html脚本无法发送post请求

代码:

$("form").submit(function (event) {

            //getting the form data
            var input_values = $(this).serializeArray();
            var post_JSON = {};
            $.each(input_values, function (i, field) {
                post_JSON[field.name] = field.value;
            });
            console.log(JSON.stringify(post_JSON));

            //Post request to mongo db
            $.post("http://localhost:5000/users/add",                   // url
                JSON.stringify(post_JSON),                              // data to be submit

                function (data, status, jqXHR) {                        // success callback
                    console.log('status: ' + status + ', data: ' + data);
                },

                "json")
                .fail(function (xhr, status, error) {
                    console.log(xhr);
                });

使用猫鼬模式定义的用户模式:

var UserSchema = new Schema({
    username: {
        type: String,
        required: true,
        trim: true,
    },
    password: {
        type: String,
        required: true,
    },
    favourites: [String],
    profile_img: Buffer,
    email: {
        type: String,
        match: /.+@.+/i, //Validates email ids
        unique: true,
        required: true,
    },
    search_history: [String],
    phone_number: {
        type: String,
        maxlength: 10,
        match: /^\d{10}$/,  //Validates phone number
    },
});

const User = mongoose.model('User', UserSchema);

module.exports = User;

这是控制台错误日志:

错误发布请求错误之前的 json 是我尝试发送到数据库的实际数据。如果我要复制粘贴此 json 并在失眠中尝试该帖子,它会起作用。但我需要它在这里工作。

【问题讨论】:

  • 当您使用 AJAX 时,您是否使用过 preventDefault() 来阻止 submit 事件实际重定向页面?
  • 另外,您能否详细说明之前的fn of undefined 错误?您在请求正文中的服务器中看到了什么?
  • 您是否在服务器上设置了body-parser

标签: jquery node.js mongodb express post


【解决方案1】:

您需要将Content-type 标头设置为application/json 以指示您的数据类型。由于Jquery.ajax 使这更容易,我建议你改用这个:

$.ajax
({
    url: 'http://localhost:5000/users/add',
    type: 'post',
    data: post_JSON,
    contentType: 'application/json',
    dataType: 'json',
    success: function (data, status, jqXHR) {
        console.log('status: ' + status + ', data: ' + data);
    },
    error: function (xhr, status, error) {
        console.log(xhr);
    }
});

【讨论】:

  • 好,但是你需要对 JSON 数据进行字符串化吗?
【解决方案2】:

您不需要在data: JSON.stringify(post_JSON) 中使用字符串化。只需发送对象,jQuery 会处理其余的事情。

【讨论】:

  • 我也尝试了一个 json 对象,但得到了相同的结果
猜你喜欢
  • 2019-06-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-13
  • 2019-04-12
  • 2023-03-28
  • 2019-09-20
  • 2016-04-06
  • 2015-06-27
相关资源
最近更新 更多