如何在NodeJS中将JSON传递到服务器?

编程入门 行业动态 更新时间:2024-10-18 22:30:12

如何在NodeJS<a href=https://www.elefans.com/category/jswz/34/1771445.html style=中将JSON传递到服务器?"/>

如何在NodeJS中将JSON传递到服务器?

我正在使用ExpressJS,MongoDB和QuillJS创建RTF博客。我正在尝试将Delta(QuillJS JSON对象通过Ajax传递给服务器)

$('#submit').click(function() {
  var delta = quill.getContents();
  console.log(delta)
  $.ajax({
    url: 'http://localhost:3000/',
    type: 'POST',
    data: {
      delta: delta
    },
    dataType: "json",
    contentType: "application/json"
  })
})

这是我的服务器

articleRouter.post('/new', async function(req, res) {
    let article = new Article({
        type: 'blog',
        title: req.body.title,
        hook: req.body.hook,
        content: req.body.delta,
        writer: req.body.writer
    })
    try {
        article = await article.save()
        res.redirect(`read/${article.slug}`)
    } catch (e) {
        console.log(e)
        res.render('index', { page: 'new', article: article, title: 'Create a new article' })
    }
})

和型号

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const slugify = require('slugify')

// Define collection and schema
let Article = new Schema({
    type: {
        type: String,
        required: true,
    },
    title: {
        type: String,
        required: true,
    },
    hook: {
        type: String,
        required: true,
    },
    content: {
        type: Object,
        required: true,
    },
    writer: {
        type: String
    },
    slug: {
        type: String,
        required: true,
        unique: true
    },
    createdAt: {
        type: Date,
        default: Date.now
    }
}, {
    collection: 'article'
})

Article.pre('validate', function(next) {
    if (this.title) {
        this.slug = slugify(this.title, { lower: true, strict: true })
    }
    next()
})

module.exports = mongoose.model('Article', Article)

我收到此错误

Error [ValidationError]: Article validation failed: content: Path `content` is required.

我相信AJAX不能正常工作,或者我在以下位置错过了东西:

content:req.body.delta,我该如何解决?

回答如下:

您是否使用猫鼬连接到MongoDB?如果是这样,请检查您的Article模式。也许content是必填字段。

更多推荐

如何在NodeJS中将JSON传递到服务器?

本文发布于:2024-05-07 08:17:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1755352.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中将   服务器   如何在   NodeJS   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!