请问,我如何停止 ValidationError 的反应?

Posted

技术标签:

【中文标题】请问,我如何停止 ValidationError 的反应?【英文标题】:Please, how do i stop ValidationError on react? 【发布时间】:2021-02-15 08:07:20 【问题描述】:

当我尝试发送帖子请求时,我收到了ValidationError: name: Path `name` is required., email: Path `email` is required., subject: Path `subject` is required., message: Path `message` is required.。我已经使用 Postman 测试了 api,并且运行良好。我已经控制台记录了状态并且工作正常,我还去了后端并从架构中删除了所需的内容,我尝试发送帖子并成功发送但是当我检查数据库时,它只是 id 和默认值发送日期。我已经尝试了我所知道的一切,我不知道还能做什么。请帮帮我。

我的反应组件

export class Contact extends Component 

  state = 
    
      name:'',
      email:'',
      subject:'',
      message:'',
 
    isSubtmit : false
  

  handleChange = (e) =>
    this.setState(
      [e.target.name] : e.target.value
      
    )
    console.log(this.state)
  

  handleSubmit = (e) =>
    console.log(this.state)
    e.preventDefault()
    if(!contact)
      console.log('invalid input')
     else
      
      const req = 
        method : 'POST', 
        header : 'Content-Type':'application/json',
        body : JSON.stringify(
        name:this.state.name,
        email: this.state.email,
        subject: this.state.subject,
        message: this.state.message
        )
      
     fetch('http://127.0.0.1:5000/contact/add', req)
     .then((res)=>res.json())
     .then(data=>console.log(data))
    
   

html

 <form >
          <div>
            <input name="name" onChange=this.handleChange value=this.state.name type="text" placeholder="Name:"/>
          </div>
          <div>
            <input name="email" onChange=this.handleChange value=this.state.email type="email" placeholder="Email:"/>
          </div>
          <div>
            <input name="subject" onChange=this.handleChange value=this.state.subject type="text" placeholder="Subject:"/>
          </div>
          <div>
          <textarea name="message" onChange=this.handleChange value=this.state.message name="message" placeholder="Message" cols="30" rows="5"></textarea>
          </div>
          <div className="form__btn">
          <button disabled=this.state.isSubtmit onClick=()=>this.setState(isSubtmit:true) onClick=this.handleSubmit>
            this.state.isSubtmit?'THANKS, SUBMITED': 'SUBMIT'
            </button>
          </div>
           </form>

我的猫鼬架构

const mongoose = require('mongoose')

const schema = mongoose.Schema

const contactSchema = new schema(
  name : 
    type: String,
    required : true,
    trim : true,
    unique : true
  ,
  email : 
    type: String,
    required : true,
    trim : true,
    unique : true
  ,
  subject : 
    type: String,
    required : true,
    trim : true,
    unique : true
  ,
  message : 
    type: String,
    required : true,
    trim : true,
    unique : true
  ,
  date : 
    type: Date,
    default:Date.now()
  ,
)

const contact = mongoose.model('contact', contactSchema)

module.exports = contact

我的特快路线

const express = require('express')
const Contact = require('../model/contacts')

// express router object 
const router = express.Router()

// post router to recieve what the user has sent to me

router.post('/add', (req, res)=>
  const name = req.body.name
  const email = req.body.email
  const subject = req.body.subject
  const message = req.body.message
  
  const item = new Contact(
    name,
    email,
    subject,
    message
  )
 
     item.save()
    .then(()=>res.json('item added'))
  
    .catch((error)=>res.status(400).json(`error : $error`))

)

module.exports = router

API 发送到http://127.0.0.1:5000/contact/add

来自后端的完整错误消息

(node:16220) UnhandledPromiseRejectionWarning: ValidationError: contact validation failed: name: Path `name` is required., email: Path `email` is required., subject: Path `subject` is required., message: Path `message` is required.
[1]     at model.Document.invalidate (C:\Users\DELL\IMV\node_modules\mongoose\lib\document.js:2626:32)
[1]     at C:\Users\DELL\IMV\node_modules\mongoose\lib\document.js:2446:17
[1]     at C:\Users\DELL\IMV\node_modules\mongoose\lib\schematype.js:1225:9
[1]     at processTicksAndRejections (internal/process/task_queues.js:79:11)
[1] (node:16220) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
[1] (node:16220) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are
not handled will terminate the Node.js process with a non-zero exit code.
[1] ReferenceError: item is not defined
[1]     at C:\Users\DELL\IMV\routes\contacts.js:25:6
[1]     at Layer.handle [as handle_request] (C:\Users\DELL\IMV\node_modules\express\lib\router\layer.js:95:5)
[1]     at next (C:\Users\DELL\IMV\node_modules\express\lib\router\route.js:137:13)
[1]     at Route.dispatch (C:\Users\DELL\IMV\node_modules\express\lib\router\route.js:112:3)
[1]     at Layer.handle [as handle_request] (C:\Users\DELL\IMV\node_modules\express\lib\router\layer.js:95:5)
[1]     at C:\Users\DELL\IMV\node_modules\express\lib\router\index.js:281:22
[1]     at Function.process_params (C:\Users\DELL\IMV\node_modules\express\lib\router\index.js:335:12)
[1]     at next (C:\Users\DELL\IMV\node_modules\express\lib\router\index.js:275:10)
[1]     at Function.handle (C:\Users\DELL\IMV\node_modules\express\lib\router\index.js:174:3)
[1]     at router (C:\Users\DELL\IMV\node_modules\express\lib\router\index.js:47:12)
[1]     at Layer.handle [as handle_request] (C:\Users\DELL\IMV\node_modules\express\lib\router\layer.js:95:5)
[1]     at trim_prefix (C:\Users\DELL\IMV\node_modules\express\lib\router\index.js:317:13)
[1]     at C:\Users\DELL\IMV\node_modules\express\lib\router\index.js:284:7
[1]     at Function.process_params (C:\Users\DELL\IMV\node_modules\express\lib\router\index.js:335:12)
[1]     at next (C:\Users\DELL\IMV\node_modules\express\lib\router\index.js:275:10)
[1]     at urlencodedParser (C:\Users\DELL\IMV\node_modules\body-parser\lib\types\urlencoded.js:100:7)

请各位大神帮忙看看是什么问题,我现在很沮丧,哭了。

【问题讨论】:

你能登录req.body吗?你在这里得到名字,电子邮件吗?从客户端看起来你正在做 JSON.stringify 使用Contact.create(name,email,subject,message)更高效 我现在就像你问的那样做了 req.body ,它返回“未定义” 我也做了 Contact.create 并且还在做同样的事情。 您应该将 header: 'Content-Type':'application/json' 更改为 headers: 'Content-Type':'application/json' (在 header 末尾带有 s ) 在你的组件中 【参考方案1】:

标题选项拼写错误。它最后缺少一个 S,所以内容是以 text/plain 而不是 application/json 的形式发送的。

变化:

const req = 
   method : 'POST', 
   header : 'Content-Type':'application/json',
   ...
 

收件人:

const req = 
   method : 'POST', 
   headers : 'Content-Type':'application/json',
   ...
 

【讨论】:

非常感谢迈克尔,你刚刚救了我的命。现在工作正常。感谢您注意到缺少的“s”。非常感谢 @Sylva 乐于助人。请将问题标记为已解决。 好吧,我不知道如何解决。我没有看到这个选项。 @Sylva meta.stackexchange.com/questions/5234/…

以上是关于请问,我如何停止 ValidationError 的反应?的主要内容,如果未能解决你的问题,请参考以下文章

如何打印ValidationError?

如何检查 Prismatic Sc​​hema 强制期间引发的 ValidationError?

c# timer停止不了,请问如何解决

如何在 Django 的 views.py 中引发 ValidationError(或做类似的事情)?

我的 log4j2 日志文件总是有每行的双输出。请问如何停止复制?

Django,在模板中显示 ValidationError