javascript - 使用 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。我究竟做错了什么?
解决方案
你在这里有一个类型:
Axios({
method: "POST",
data: newNote, <-------- // should be newNotes, maybe?
withCredentials: true,
url: `http://localhost:4000/note/${props.userid}`,
})
newNote
变量是什么类型?只是一个字符串?然后我猜您想将newNotes
变量(对象)用于 axios 请求。因为您使用邮递员在本地执行的请求也使用了一个对象(注意字符串包含在: 中{ note: "content"}
)。
推荐阅读
- python - 确定列表是否是周期性的python
- javascript - 如何使此滑块在单击下一个和上一个时显示 2 个引号
- python - python中多个可能参数组合的条件结构
- tensorflow - 我训练了一个神经网络,但我找不到它的保存位置,我找不到任何 .meta 、 .index 、 .data 文件
- wordpress - 从过去 3 天开始,收到大量来自美国的垃圾邮件流量,如何阻止?
- sql - golang null.String 解码无法正常工作
- cordova - 我们有用于 aws-cognito-identity 的 cordova 插件吗?
- html - 在 HTML/CSS 中访问链接时使图像变为灰度
- angular - 添加解析器和动态布局组合后,Angular 8 组件不显示
- selenium - 获取“无法启动 Selenium 侦听器”。通过 saucelabs 运行 testcafe 脚本时出现错误消息