如何解决MERN stack) 如何在发布项目后从客户端获取节点 js 数据?
第一次在stackoverflow上发帖。我已经阅读了有关此问题的大多数帖子,但仍然无法弄清楚。
我正在尝试创建一个项目并将其 ID 显示在控制台上,但它给出了空对象。
课程控制器
create(req,res){
const newCourse = new Course(req.body);
newCourse.save()
.then(res => {
console.log("res: ",res)
res.json(res)
})
.catch(err => res.json(err));
}
这是我的控制器。我相信在我创建一个新项目之后。 它应该以json格式向客户端发送res数据。
创建课程后的后端结果
res: {
students: [],_id: 602c112321950b4f9ca207d6,name: 'hello',capacity: 32,professor: '602b567ce023da4f282703b9',__v: 0
}
客户
const newCourse = {
name : courseName,capacity : courseCapacity,professor: user.id
}
axios.post('http://localhost:8000/api/Courses',newCourse)
.then(res => {
console.log(res) /// gives empty object {}
console.log(JSON.parse(res.config.data))
user.courses = [...user.courses,JSON.parse(res.config.data)]
console.log(user.courses)
// axios.put(`http://localhost:8000/api/users/${user.id}`,{ courses: user.courses })
// .then(res => console.log(res))
// .catch(err => console.log(err))
})
.catch(err => console.log(err))
这里我使用了 json.parse(res.config.data)) 因为它返回空对象 res 数据。
客户端 console.log(res)
{data: {…},status: 200,statusText: "OK",headers: {…},config: {…},…}
config: {url: "http://localhost:8000/api/Courses",method: "post",data: "{"name":"hello","capacity":"32","professor":"602b567ce023da4f282703b9"}",transformRequest: Array(1),…}
data: {}
headers: {content-length: "2",content-type: "application/json; charset=utf-8"}
request: XMLHttpRequest {readyState: 4,timeout: 0,withCredentials: false,upload: XMLHttpRequestUpload,onreadystatechange: ƒ,…}
status: 200
statusText: "OK"
__proto__: Object
使用我的用户模型获取数据对象没有问题。 除了 res.data 之外,一切都很好。它创建的过程非常好。 我以为我的服务器端有问题,我尝试以不同的格式发送,但我不知道我在这里遗漏了什么。
提前致谢。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。