node.js - 前端提取不起作用,但后端显示 API
问题描述
我一直在尝试从后端获取用户的数据,以将其设置为我的应用程序前端的状态。我正在使用 MERN 堆栈。我正处于学习阶段。做一个关于学习的直接项目过程
app.get("/api/users",(req , res )=>{
console.log(req.session.passport.user)
Users.find({"_id":req.user._id},(err,user)=>{
if(err) {console.log(err)}
const userjson = JSON.stringify(user)
res.end(userjson)
})
})
这里的用户是数据库模型,在前端部分我已经通过 axios 完成了获取
import React,{useEffect, useState,Component} from 'react'
import SectionBar from '../../../Header/NavigationItems/SectionBar'
import AdminShop from './Shop/Shop'
import { Route, Switch } from 'react-router'
import Products from './Products/products'
import Profile from './Profile/Profile'
import axios from 'axios'
class AdminLayout extends Component {
constructor(props){
super(props)
this.state={
user:{},
contetShow:false
}
}
componentDidMount() {
axios.get("http://localhost:4000/api/users").then((response)=>{
console.log(response)
this.setState({
...this.state,
user:response.data,
contentShow:true
})
})
.catch((err)=>{
this.setState({
...this.state,
contentShow:false
})
})
}
render() {
const sectionLink = ["shop","products","profile"]
let Display = this.state.contentShow?<>
<SectionBar tag ="admin" links={sectionLink}/>
<Switch>
<Route path="/admin/shop" exact component={AdminShop}/>
<Route path="/admin/products" exact component={Products}/>
<Route path="/admin/profile" exact component={Profile}/>
</Switch>
</>:<p>Nothing to display</p>;
return (
<>
{Display}
</>
)
}
}
export default AdminLayout
我期待着回复
解决方案
似乎不需要JSON.stringify
在后端调用。前端可以将其作为原始 json 接收。
以下代码段应该有助于解决您的问题。
app.get("/api/users", (req, res )=>{
console.log(req.session.passport.user)
Users.find({"_id":req.user._id},(err,user)=>{
if(err) {console.log(err)}
res.status(200).json({
status: 'success',
data: user,
});
})
})
然后,像下面的代码片段一样在前端调用它。
axios.get("http://localhost:4000/api/users").then((response)=> {
this.setState({
...this.state,
user: response.data,
contentShow: true
});
推荐阅读
- java - 如何在 SeekableByteChannel 上获得进程间锁?
- javascript - 每个 amchart 切片的自定义渐变颜色
- c++ - SAM 中的 AWS lambda C++ 运行时
- selenium - 如何从 surefire-reports testng-results.xml 获取 jenkins 测试报告链接?
- daml - 无法编译测试 DAML 模块
- angular - 提交表单后,Angular Material 7 错误重置自动完成
- java - Jave 类型参数方法和构造函数问题
- python - bins - 使用年龄的 bin 对列值进行分类
- javascript - 访问 Javascript 脚本中的 C# 对象
- python - 替换和迭代多维 np.matrix 的 x 轴和 y 轴