postman Mongoose:Undefine Data Error when I try to send data from frontend to backend in react app

6yoyoihd  于 12个月前  发布在  Postman
关注(0)|答案(1)|浏览(125)

我试图创建与mongo altasReact应用程序.我有第一次测试所有的API和Postman上的方法,他们工作正常.然后我创建一个联系我们页面,并尝试连接前端与后端.在点击notting似乎发生,但创建功能被调用.添加几个检查后,我发现未定义的数据将mongoose. idk我在这里做错了什么.
我可以提供更多的信息,但我不知道还有什么给予。这里是控制器文件

const Form = require('../models/database')
const mongoose = require("mongoose")

//create a form
const createForm = async (req, res) => {
    const { name, email, message } = req.body;

    // Log received data
    console.log('Received data:', { name, email, message });

    try {
        // Attempt to create a new form
        const form = await Form.create({ name, email, message });

        // Log created form
        console.log('Form created:', form);

        // Respond with the created form
        res.status(200).json(form);
    } catch (error) {
        // Log any errors
        console.error('Error creating form:', error);

        // Respond with an error message
        res.status(400).json({ error: error.message });
    }
}

字符串
这里是前端接触组件

import { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';

const ContactUs = () => {
  const [name, setName] = useState('')
  const [email, setEmail] = useState('')
  const [message, setMessage] = useState('')
  const [error, setError] = useState(null)

  const handleSubmit = async (e) => {
    e.preventDefault()

    const formm = {name, email, message}

    const response = await fetch('/api/forms',{
      method: 'POST',
      body: JSON.stringify(formm)
    })
    const json = await response.json()

    if (!response.ok){
      setError(json.error)
    }
    if (response.ok){
      setName('')
      setEmail('')
      setMessage('')
      setError(null)
      console.log('Form added ', json)
    }
  }

  return (
    <>
      <html lang="en">
        <body>
          <header>
            <h1>Contact Us</h1>
          </header>
          <section>
            <form className='contactus' onSubmit={handleSubmit}>
              <label>Name:</label>
              <input type="text"  onChange={(e) => setName(e.target.value)} value={name}/>

              <label>Email:</label>
              <input type="text" onChange={(e) => setEmail(e.target.value)} value={email} />

              <label>Message:</label>
              <textarea onChange={(e) => setMessage(e.target.value)} value={message} />

              <div className="button-group">
                <button type="submit">Submit</button>
                <button type="button" className="delete-button">Delete</button>
                <button type="button" className="modify-button">Modify</button>
              </div>
            </form>
          </section>
          <footer>
            <Link to="/Main">
              <button>Home</button>
            </Link>
            <p>&copy; 2023 BeancIncc. </p>
          </footer>
        </body>
        <style jsx>{` `}</style>
      </html>
    </>
  );
}

export default ContactUs;


这是我得到的错误。

Database is listing on port 4000
/api/forms POST
Received data: { name: undefined, email: undefined, message: undefined }
Error creating form: Error: Form validation failed: name: Path `name` is required., email: Path `email` is required., message: Path `message` is required.
    at ValidationError.inspect (E:\Semester 5\Projects\Beanc-Incc-React (Web Engineering)\backend\node_modules\mongoose\lib\error\validation.js:50:26)
    at formatValue (node:internal/util/inspect:805:19)
    at inspect (node:internal/util/inspect:364:10)
    at formatWithOptionsInternal (node:internal/util/inspect:2298:40)
    at formatWithOptions (node:internal/util/inspect:2160:10)       
    at console.value (node:internal/console/constructor:351:14)     
    at console.warn (node:internal/console/constructor:384:61)      
    at createForm (E:\Semester 5\Projects\Beanc-Incc-React (Web Engineering)\backend\controller\formsControllers.js:44:17)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  errors: {
    name: ValidatorError: Path `name` is required.
        at validate (E:\Semester 5\Projects\Beanc-Incc-React (Web Engineering)\backend\node_modules\mongoose\lib\schemaType.js:1365:13) 
        at SchemaType.doValidate (E:\Semester 5\Projects\Beanc-Incc-React (Web Engineering)\backend\node_modules\mongoose\lib\schemaType.js:1349:7)
        at E:\Semester 5\Projects\Beanc-Incc-React (Web Engineering)\backend\node_modules\mongoose\lib\document.js:2972:18
        at process.processTicksAndRejections (node:internal/process/task_queues:77:11) {
      properties: [Object],
      kind: 'required',
      path: 'name',
      value: undefined,
      reason: undefined,
      [Symbol(mongoose#validatorError)]: true
    },
    email: ValidatorError: Path `email` is required.
        at validate (E:\Semester 5\Projects\Beanc-Incc-React (Web Engineering)\backend\node_modules\mongoose\lib\schemaType.js:1365:13) 
        at SchemaType.doValidate (E:\Semester 5\Projects\Beanc-Incc-React (Web Engineering)\backend\node_modules\mongoose\lib\schemaType.js:1349:7)
        at E:\Semester 5\Projects\Beanc-Incc-React (Web Engineering)\backend\node_modules\mongoose\lib\document.js:2972:18
        at process.processTicksAndRejections (node:internal/process/task_queues:77:11) {
      properties: [Object],
      kind: 'required',
      path: 'email',
      value: undefined,
      reason: undefined,
      [Symbol(mongoose#validatorError)]: true
    },
    message: ValidatorError: Path `message` is required.
        at validate (E:\Semester 5\Projects\Beanc-Incc-React (Web Engineering)\backend\node_modules\mongoose\lib\schemaType.js:1365:13) 
        at SchemaType.doValidate (E:\Semester 5\Projects\Beanc-Incc-React (Web Engineering)\backend\node_modules\mongoose\lib\schemaType.js:1349:7)
        at E:\Semester 5\Projects\Beanc-Incc-React (Web Engineering)\backend\node_modules\mongoose\lib\document.js:2972:18
        at process.processTicksAndRejections (node:internal/process/task_queues:77:11) {
      properties: [Object],
      kind: 'required',
      path: 'message',
      value: undefined,
      reason: undefined,
      [Symbol(mongoose#validatorError)]: true
    }
  },
  _message: 'Form validation failed'
}


数据库:

const mongoose = require("mongoose")

const FormSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    message: {
        type: String,
        required: true
    }
}, {timestamps:true} );

module.exports = mongoose.model( 'Form', FormSchema)


尝试重新创建数据库。检查本地主机和变量名

qacovj5a

qacovj5a1#

首先打印formm对象,确保它是正确的

console.log('Form data:', formm);

字符串
然后如果没有问题,试着检查内容类型和你的fetch方法使用的url。

const response = await fetch('http://localhost:3000/api/forms', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(formm),
});


我有一个硬编码的localhost:3000作为例子,你可以用你的实际URL替换它。
坦率地说,这应该是它,有一个轻微的机会,国家的价值观没有得到更新,所以让我知道是什么情况。

相关问题