最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

网站源码admin15浏览0评论

如何在NodeJS中将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是必填字段。

发布评论

评论列表(0)

  1. 暂无评论