繁体   English   中英

帖子请求正文为空

[英]Body of post request is empty

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

然而,这个与express服务器在同一目录下的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 并在失眠中尝试该帖子,它会起作用。 但我需要它在这里工作。

您需要将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);
    }
});

您不需要在data: JSON.stringify(post_JSON)使用 stringify data: JSON.stringify(post_JSON) 只需发送对象,jQuery 会处理剩下的事情。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM