使用axios将数据放入我的数据库的问题



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

User.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/注意/603 ca08df021760f000aa1bb→"userid">

{
"note":"hey"
}

它工作得很好,我有注释"在我的db上。但当我尝试通过axios做那个请求时,我注意到null。我做错了什么?

这里有一个类型:

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

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

最新更新