【发布时间】: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