【问题标题】:Issue with putting data to my database using axios使用 axios 将数据放入我的数据库的问题
【发布时间】:2023-03-16 09:19:01
【问题描述】:

当我可以唱歌、唱歌、做笔记并在前端显示它们时,我正在学习 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。我做错了什么?

【问题讨论】:

  • 在你的函数服务器端添加一个打印来打印req.body的值我想你会看到它没有像你一样格式化。

标签: javascript node.js reactjs express axios


【解决方案1】:

你在这里有一个类型:

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

newNote 变量是什么类型的?只是一个字符串?那我猜你想使用newNotes 变量(对象)来进行axios 请求。因为您使用 postman 在本地执行的请求也使用了一个对象(注意字符串包含在:{ note: "content"})。

【讨论】:

  • 好吧,看来我是个白痴,我传递了错误的变量。谢谢这是正确的解决方案
  • 很高兴能帮到你:)。请接受它作为解决方案:)。
猜你喜欢
  • 2019-09-20
  • 1970-01-01
  • 2011-09-08
  • 2015-04-04
  • 2011-09-06
  • 2019-10-10
  • 2022-11-13
  • 2016-03-17
  • 2011-02-12
相关资源
最近更新 更多