如何解决前端提取不工作,但后端显示 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)
})
})
这里Users是数据库模型,在前端部分我已经通过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
期待回复
解决方法
您的构造函数中似乎有一个拼写错误.. this.state 有 contetshow=false
,但您在应用程序中使用了 contentshow
。现在这应该无关紧要,因为您描述的错误是类型错误,表示您缺少值。 console.log(response)
的结果是什么?这可能不包含数据,这就是为什么您的 user
未定义
似乎不需要在后端调用 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
});
,
class App extends Component {
constructor(props) {
super(props);
this.state = {
user: {},contetShow: false
};
}
async componentDidMount() {
try{
let rs = await axios.get("http://localhost:4000/api/users")
if (rs){
this.setState({user : rs.data})
this.setState({contentShow : true})
}
}
catch(e){
return this.setState({contentShow : false})
}
}
render() {
return (
<>
{this.state.contentShow ? (
// your Code
console.log("user",this.state.user)
) : (
<p>Nothing to display</p>
)}
</>
);
}
}
export default App;
如果您在控制台中未定义用户,请检查开发者工具中的网络选项卡可能是您的后端有问题
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。