首页 > 解决方案 > 使用 axios 将数据放入我的数据库的问题

问题描述

当我可以唱歌、唱歌、做笔记并在前端显示它们时,我正在学习 mern stack 并正在构建简单的应用程序。除了一件事,一切都很好。当我试图通过 axios 传递 null 而不是我的笔记来完成新的笔记请求时。

用户.js

const mongoose = require('mongoose')
const userSchema = new mongoose.Schema({
    username: {type:String,required:true },
    password: {type:String ,required:true},
    note: [{type:String}]
})

module.exports = mongoose.model("User", userSchema)

注意端点

app.post('/note/:user',(req,res) => {
    userSchema.findByIdAndUpdate(req.params.user)
      .then(foundUser => {
        foundUser.note = [...foundUser.note,req.body.note]

        foundUser.save()
          .then(() => res.json("note added"))
      })
})

Notes.js

import Axios from 'axios'


function Notes(props){
    const [notes,setNotes] = useState()
    const [newNote,setNewNote] = useState('')
    useEffect(() => {
        setNotes(props.note)
       
      }, [props.note])
    useEffect(() => {
        
    }, [notes]);
    

    const handleChange = (e) =>{
        setNewNote(e.target.value)
    }
    const handleSubmit = (e) =>{
        e.preventDefault()
        console.log(newNote)
        const newNotes = {
            note : newNote
        }
        console.log(newNotes)
        Axios({
            method: "POST",
            data: newNote,
            withCredentials: true,
            url: `http://localhost:4000/note/${props.userid}`,
          })
    }
    return(
        <div>
            {
                notes ? notes.map(e => {
                    return (
                    <div> {e} </div>

                    )
                }) : null
            }
            <form onSubmit={handleSubmit}>
                <input
                type='text'
                value={newNote}
                onChange={handleChange}/>
                <button type="submit">Add</button>
            </form>
        </div>
    )
}

export default Notes

当我传递一些笔记然后我查看我的数据库而不是查看我的新笔记时,我看到“null”。当我对邮递员提出完全相同的要求时,这很奇怪

前任。http://localhost:4000/note/603ca08df021760f000aa1bb->“用户ID”

{
    "note":"hey"
}

它工作得很好,我的数据库上有注释“嘿”。但是当我尝试通过 axios 执行该请求时,我注意到 null。我究竟做错了什么?

标签: javascriptnode.jsreactjsexpressaxios

解决方案


你在这里有一个类型:

  Axios({
    method: "POST",
    data: newNote, <-------- // should be newNotes, maybe?
    withCredentials: true,
    url: `http://localhost:4000/note/${props.userid}`,
  })

newNote变量是什么类型?只是一个字符串?然后我猜您想将newNotes变量(对象)用于 axios 请求。因为您使用邮递员在本地执行的请求也使用了一个对象(注意字符串包含在: 中{ note: "content"})。


推荐阅读