【发布时间】: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