[英]Frontend fetch not working but backend shows the API
我一直在嘗試從后端獲取用戶數據,以便在我的應用程序前端將其設置為 state。 我正在使用 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 是數據庫 model 並且在前端部分我已經通過 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;
如果您在控制台中未定義用戶,請檢查開發人員工具中的網絡選項卡可能是您的后端有問題
import React, { Component } from 'react';
import KonyvList from './KonyvList';
import KonyvForm from './KonyvForm';
import KonyvtarFooter from './KonyvtarFooter';
import KonyvtarHeader from './KonyvtarHeader';
class KonyvtarApp extends Component {
constructor(props) {
super(props);
this.state = {
books: [],
title: "",
author: "",
publish_year: "",
page_count: "",
errors: "",
};
}
componentDidMount() {
this.getKonyvek();
}
render() {
const form_id = "konyv_form";
const { books, title, author, publish_year, page_count, errors } = this.state;
const form_state = {
title: title,
author: author,
publish_year: publish_year,
page_count: page_count,
errors: errors
};
return (
<div className="container mb-3">
<KonyvtarHeader form_id={form_id} />
<main className='mt-3 mb-3'>
<KonyvList books={books} rentClick={this.handleRent} />
<KonyvForm form_id={form_id} formState={form_state}
onTitleInput={this.handleTitleInput}
onAuthorInput={this.handleAuthorInput}
onPublishYearInput={this.handlePublishYearInput}
onPageCountInput={this.handlePageCountInput}
onClick={this.handleFelvetel}
/>
</main>
<KonyvtarFooter keszito="" />
</div>
);
}
handleTitleInput = (value) => {
this.setState({
title: value
});
}
handleAuthorInput = (value) => {
this.setState({
author: value
});
}
handlePublishYearInput = (value) => {
this.setState({
publish_year: value
});
}
handlePageCountInput = (value) => {
this.setState({
page_count: value
});
}
handleFelvetel = () => {
const { title, author, publish_year, page_count } = this.state;
const book = {
title: title,
author: author,
publish_year: publish_year,
page_count: page_count,
};
fetch("http://localhost:8000/api/books", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(book)
}).then(async response => {
if (response.status === 201) {
this.setState({
title: "",
author: "",
publish_year: "",
page_count: "",
errors: "",
})
this.getKonyvek();
} else {
const data = await response.json();
this.setState({
errors: data.message
})
}
});
}
async getKonyvek() {
fetch("http://localhost:8000/api/books")
.then(async response => {
if (response.status === 200) {
const data = await response.json();
this.setState({
books: data.data
})
}
});
}
}
export default KonyvtarApp;
應用程序.js:
import KonyvtarApp from './KonyvtarApp';
function App() {return (<KonyvtarApp />);}
export default App;
KonyvCard.jsx:
import React, { Component } from 'react';
class KonyvCard extends Component {
constructor(props) {
super(props);
this.state = {
errors: "",
rented: false
};
}
handleRent = (book_id) => {
fetch(`http://localhost:8000/api/books/${book_id}/rent`, {
method: "POST",
}).then(async response => {
if (response.status === 200) {
this.setState({
errors: "",
rented: true
})
} else {
const data = await response.json();
this.setState({
errors: data.message,
rented: false
})
}
});
}
render() {
const { book } = this.props;
const { rented, errors } = this.state;
return (
<div className="col-sm-12 col-md-6 col-lg-4 card">
<div className="card-body">
<h2>{book.title}</h2>
<h2>{book.author}</h2>
<p>Kiadási év: {book.publish_year}</p>
<p>Hossz: {book.page_count} oldal</p>
<img className='img-fluid' src={'szerzok/' + book.author + '.jp g'} alt={book.author} />
<button className='btn btn-light mt-3' onClick={() => this.handleRent(book.id)}>Kölcsönzés</button>
<p>
{rented ? "Sikeres foglalás" : errors !== "" ? errors : ""}
</p>
</div>
</div>
);
}
}
export default KonyvCard;
KonyvCard.jsx:
//imrc
import React, { Component } from 'react';
///cc
class KonyvCard extends Component {
constructor(props) {
super(props);
this.state = {errors: "",rented: false};}
handleRent = (book_id) => {
fetch(`http://localhost:8000/api/books/${book_id}/rent`, {method: "POST",}).then(async response => {
if (response.status === 200) {this.setState({errors: "",rented: true})
} else {
const data = await response.json();
this.setState({
errors: data.message,
rented: false})}});}
render() {
const { book } = this.props;
const { rented, errors } = this.state;
return (<div className="col-sm-12 col-md-6 col-lg-4 card">
<div className="card-body">
<h2>{book.title}</h2>
<h2>{book.author}</h2>
<p>Kiadási év: {book.publish_year}</p>
<p>Hossz: {book.page_count} oldal</p>
<img className='img-fluid' src={'szerzok/' + book.author + '.jpg'} alt={book.author} />
<button className='btn btn-light mt-3' onClick={() => this.handleRent(book.id)}>Kölcsönzés</button>
<p>
{rented ? "Sikeres foglalás" : errors !== "" ? errors : ""}
</p>
</div>
</div>);}}
//export
export default KonyvCard;
申請.css
.App { text-align: center;}
.App-logo {
高度:40vmin; 指針事件:無;}
@media (prefers-reduced-motion: no-preference) {
.App-logo {animation: App-logo-spin infinite 20s linear;}}
.App-header {background-color: #282c34;min-height: 100vh;display: flex;
flex-direction: column;align-items: center;justify-content: center;
font-size: calc(10px + 2vmin);color: white;}
.App-link {color: #61dafb;}
應用程序.js
import './App.css';
import PeopleList from './PeopleList'; //importálni kell!!!
//import bootstrap annak npm install bootstrap után
導入“bootstrap/dist/css/bootstrap.min.css”; 導入“bootstrap/dist/js/bootstrap.bundle.min”;
function App() {return (
<div className="container">
<PeopleList />
</div>);}
export default App;
// új komponens létrehozásával kezdjük: PeopleList.jsx
索引.js:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
ReactDOM.render(<React.StrictMode><App /></React.StrictMode>,
document.getElementById('root'));
人物名片:
//imrc
import React, { Component } from 'react';
///cc
class PeopleCard extends Component {
render() {const { people, torlesClick } = this.props;
return ( <div className="col-sm-6 cold-md-4 col-lg-3
PeopleCard">
<div className="card h-100 PeopleCard-card">
<div className="card-header text-truncate PeopleCard-card-header"><span className="font-weight-bold">Name: </span>
{people.name}
</div>
<div className="card-body PeopleCard-card-body">
<ul className="list-group list-group-flush">
<li className="list-group-item"><span className="font-weight-bold">Email: </span>{people.email}</li>
<li className="list-group-item"><span className="font-weight-bold">Age: </span>{people.age}</li>
</ul>
</div>
<div className="card-footer">
<button onClick={() => torlesClick(people.id)} className="btn btn-danger">Törlés</button>
</div>
</div>
</div> );
}
}
導出默認的 PeopleCard;
PeopleList.jsx 與 jsx 文件格式 (előnye emet bővítmény működni fog és alt+shit+f -el tudok formázni) ehhez importálnom kell a react-et, imr vagy imrc parancs kiadásával import React, { 'Component } from 'react ; 從“./PeopleCard”導入 PeopleCard; cc - vel egy class componentet tudok létrehozni vagy ccc konstruktorral PeopleL
class PeopleList extends Component {
constructor(props) {
super(props);
this.state = {
people: []}}
componentDidMount() {
this.getPeople();}
getPeople(){
fetch("http://localhost:8000/api/people")
.then(response => response.json())
.then(data => this.setState({
people: data
}));}
handleTorlesClick = (id) => {
fetch(`http://localhost:8000/api/film/${id}`, {method: "DELETE"})
.then(response => console.log(response))}
render(){
// CardList listába veszem fel
const {people} = this.state;
const cardList = [];
people.forEach(people => {
cardList.push(<PeopleCard torlesClick={this.handleTorlesClick} key={people.id} people={people} />);
});;
return ( <div className="row gy-3">
{cardList}
<PeopleCard people={people}/>
</div> );}
}
導出默認人員列表; //card megjelenítése npm start-al leellenőrzöm, --> localhost:3000; App.js-ben //megjelenítése szükséges (teszt) vagy CardList
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.